Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC validator annotation + custom validation

I'm working on spring mvc application, where I should aplly validation based on Spring MVC validator. I first step for that I added annotation for class and setup controller and it works fine. And now I need to implement custom validator for perform complex logic, but i want to use existing annotation and just add additional checking.

My User class:

public class User {     @NotEmpty     private String name;      @NotEmpty     private String login; // should be unique } 

My validator:

@Component public class UserValidator implements Validator {      @Autowired     private UserDAO userDAO;      @Override     public boolean supports(Class<?> clazz)     {         return User.class.equals(clazz) || UsersForm.class.equals(clazz);     }      @Override     public void validate(Object target, Errors errors)     {         /*         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotEmpty.user");         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "NotEmpty.user");         */         User user = (User) target;         if (userDAO.getUserByLogin(user.getLogin()) != null) {             errors.rejectValue("login", "NonUniq.user");         }     } } 

My controller:

@Controller public class UserController {     @Autowired     private UserValidator validator;      @InitBinder     protected void initBinder(final WebDataBinder binder)     {         binder.setValidator(validator);     }      @RequestMapping(value = "/save")     public ModelAndView save(@Valid @ModelAttribute("user") final User user,             BindingResult result) throws Exception     {         if (result.hasErrors())         {             // handle error         } else         {             //save user         }     } } 

So, Is it possible to use custom validator and annotation together? And if yes how?

like image 668
Vartlok Avatar asked Aug 01 '14 08:08

Vartlok


People also ask

What is the purpose of custom Validator annotation?

A custom validation annotation can also be defined at the class level to validate more than one attribute of the class. A common use case for this scenario is verifying if two fields of a class have matching values.

What is the purpose of custom validations in Spring MVC?

The Spring MVC Validation is used to restrict the input provided by the user. To validate the user's input, the Spring 4 or higher version supports and use Bean Validation API. It can validate both server-side as well as client-side applications.

What is custom validation in MVC?

This validation can be added for both the client side and the server side. You understand that decorating the properties in a model with an Attribute can make that property eligible for Validation. Some of the DataAnnotation used for validation are given below. Required. Specify a property as required.


1 Answers

I know this is a kind of old question but, for googlers...

you should use addValidators instead of setValidator. Like following:

@InitBinder protected void initBinder(final WebDataBinder binder) {     binder.addValidators(yourCustomValidator, anotherValidatorOfYours); } 

PS: addValidators accepts multiple parameters (ellipsis)

if you checkout the source of org.springframework.validation.DataBinder you will see:

public class DataBinder implements PropertyEditorRegistry, TypeConverter {      ....      public void setValidator(Validator validator) {         assertValidators(validator);         this.validators.clear();         this.validators.add(validator);     }      public void addValidators(Validator... validators) {         assertValidators(validators);         this.validators.addAll(Arrays.asList(validators));     }      ....  } 

as you see setValidator clears existing (default) validator so @Valid annotation won't work as expected.

like image 191
destan Avatar answered Oct 19 '22 22:10

destan