Search code examples
springhibernate-validatorcustomvalidator

can @Email and spring custom validation coexists?


I need to validate Email and password while creating an account using web services. I am using Spring REST controller and plan to use @Email(hibernate validator) annotation for email id validation.For Password validation I have to write custom validator by implementing Validator interface.

@XmlRootElement
public class Account implements Serializable {

    @Email(message =AccountErrorCodes.ACCOUNT_EMAIL_VALIDATION)
    private String emailId;

    private String password;

For password writing the own validator

@Autowired
private PasswordValidator passwordValidator;

@InitBinder
private void initBinder(WebDataBinder binder) {
    binder.setValidator(passwordValidator);
}

It looks like both cant coexist. When I try to validate EmailId spring calls passwordValidator but fails to validate Email. I expect the failure due to incorrect Email id. When I disable the custom validator I get the required error message.

Looks like I am missing something. Do I need to do something to make it work? or it is not supported? If not supported Can I call Hibernate validator directly from spring custom validator to avoid writing my own validation for email?


Solution

  • Instead of injecting your custom validator in your controller, make a special @Password annotation for it that uses this as a validator. Remove any constraint logic from controller and do it all on your DTO class. Something like this:

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

    You will find loads of tutorials for custom annotations that use your own made validators. Hope that helps.