spring mvc nested model validation

前端 未结 4 1818
梦毁少年i
梦毁少年i 2020-12-18 10:01

I have two models : User,Project

public class Project{
    private int id;
    @NotEmpty(message=\"Project Name can not be empty\")
    private          


        
4条回答
  •  北海茫月
    2020-12-18 10:48

    I did what Jerome Dalbert suggested and in addition added a custom BeanValidator for delegating the actual work of validating to a JSR 303 implementation.

    The prefix is used to denote the path of the property in the form.

    @Component
    public class BeanValidator implements org.springframework.validation.Validator, InitializingBean {    
    
     private Validator validator;
     public void afterPropertiesSet() throws Exception {
      ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
      validator = validatorFactory.usingContext().getValidator();
     }
    
     public boolean supports(Class clazz) {
      return true;
     }
    
     public void validate(Object target, Errors errors, String prefix) {
      Set> constraintViolations = validator.validate(target);
      for (ConstraintViolation constraintViolation : constraintViolations) {
       String propertyPath = constraintViolation.getPropertyPath().toString();
       String message = constraintViolation.getMessage();
       errors.rejectValue(prefix + "." + propertyPath, "", message);
      }
     }
    
     public void validate(Object target, Errors errors) {
      validate(target, errors, "");
     }
    }
    
    
    

    and here how I used it in the UserValidator:

    @Component
    public class UserValidator implements Validator {
    
     @Autowired
     BeanValidator beanValidator;
    
     @Override
     public boolean supports(Class clazz) {
      return User.class.equals(clazz);
     }
    
     @Override
     public void validate(Object target, Errors errors) {
      User user = (User) target;
      beanValidator.validate(user.getAddress(), errors, "address");
     }
    }
    

    References:

    • http://blog.trifork.com/2009/08/04/bean-validation-integrating-jsr-303-with-spring/

    提交回复
    热议问题