Spring Hibernate Validator check step by step

404 views Asked by At

I had many constraint on a single property, like this:

@NotEmpty
@Size(min = 2, max = 20)
@Pattern(regexp= "^[0-9a-z_A-Z\u4e00-\u9fa5]+$")
private String username;

but, when it works, it will check all constraints, and I just want check step by step, so how can i do? and I found a special constraint, that is @Email constraint, I do like this:

@NotEmpty
@Email
private String email;

I found it will check step by step, if the @NotEmpty constraint check failed, it will not check @Email constraint, I just found @Email have the function, I want to say, there is some especial for @Email?

It is so confused for me, and I hoped someone could help me, thanks.

2

There are 2 answers

0
Aeseir On BEST ANSWER

Sounds like you should look into creating a custom validator.

here is a good example on how to setup a basic custom validator (go to section called Custom Validator Implementations, especially the way they do the EmployeeFormValidator): http://www.journaldev.com/2668/spring-mvc-form-validation-example-using-annotation-and-custom-validator-implementation

Creata a custom ordering in there that you want to have and then just bind it within your controller against your expected object (or call the validate function.

0
CE ZHANG On

If you are gonna use JSR-303, that is what you are doing in your code and custom validator, it's not easy for you control the order of validation. Therefore, better to transform all those validation in a custom validator, it's much more flexible.

(1)Implements the Spring validator interface

public XXXValidator implements Validator {

     @Autowired MessageSource messageSource
        public boolean supports(Class clazz) {
                return XXXX.class.equals(clazz);
         }

        public void validate(Object obj, Errors e) {
            //do your validation here
           if(....){
                  e.rejectValue(..,..,messageSource.getMessage(...),..,..)
           }
        }
    }

(2) in you controller

XXXValidator validator=new XXXValidator ();
@RequestMapping(...,....)
public String handlePostMethodExample(@ModelAndAttribute XXX xxx,BindingResult error)
  validator.validate({instance of XXX object here});
  if(error.hasErrors(){
   //handle error here
  }
}