Skip to content
Advertisement

How to join several validation annotations

I have following annotation to validate password:

JavaScript

But spring validation does not recognize this rules. I used this annotation as:

JavaScript

How can I get it without defining ConstraintValidator instance?

Advertisement

Answer

If you want to use ConstraintValidator, you can do it like this:

create Password annotation :

JavaScript

then create the PasswordConstraintValidator class :

JavaScript

Then apply it to one of your fields, note that you can also put a custom message:

JavaScript

You can also refactor the if statements each in an appropriate method (to have a clean code): something that will look like this :

JavaScript

Update

since you don’t want to use the ConstraintValidator, your implementation looks fine, you just need to add @Valid on your model so that cascading validation can be performed and include spring-boot-starter-validation to make sure that validation api is included and add @Constraint(validatedBy = {}) on your custom annotation. Here is a groovy example here (you can run it with spring CLI) :

JavaScript

So when you curl :

JavaScript

you will get an error validation response :

JavaScript
Advertisement