1

I am using JSR-303 in Spring to validate a password field. I would like to put all my validation logic in one class and display the message for each error accordingly. Is this possible? Is it a better practice to create a separate class for each validation check (i.e. PasswordLengthValidator, PasswordRegexValidator)?

Currently, I am able to display only 1 error message based on the Password interface.

Here is my interface for the @Password annotation:

@Documented @Constraint(validatedBy = PasswordValidator.class) @Target( { ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Password { String message() default "{Password}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } 

Here is my validator class:

public class PasswordValidator implements ConstraintValidator<Password, String> { public void initialize(Password arg0) { // TODO Auto-generated method stub } public boolean isValid(String field, ConstraintValidatorContext ctx) { // TODO validation validation validation if(StringUtils.isEmpty(field)) { // Message: password can not be empty return false; } // match some password regex if(field.matches("^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$")) { // Message: password should be bla bla return false; } return true; } } 

1 Answer 1

1

Your validator can send validation messages with the ConstraintValidatorContext API:

context.buildConstraintViolationWithTemplate( "this detail is wrong" ) .addConstraintViolation(); // [..] context.buildConstraintViolationWithTemplate( "that detail is wrong" ) .addPropertyNode( "street" ) .addConstraintViolation(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.