2014-01-16 82 views
1

我在Spring中使用JSR-303來驗證密碼字段。我想將我的所有驗證邏輯放在一個類中,並相應地顯示每個錯誤的消息。這可能嗎?爲每個驗證檢查(例如PasswordLengthValidator,PasswordRegexValidator)創建一個單獨的類是否更好?Spring MVC驗證:爲每個驗證檢查設置特定的錯誤消息

目前,我只能根據密碼界面顯示1條錯誤消息。

這裏是我的@Password註釋接口:

@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 {}; 

} 

這裏是我的驗證器類:

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])(?=.*[[email protected]#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$")) { 
      // Message: password should be bla bla 
      return false; 
     } 

     return true; 
    } 

} 

回答

1

您的驗證可以發送與ConstraintValidatorContext API驗證消息:

context.buildConstraintViolationWithTemplate("this detail is wrong") 
     .addConstraintViolation(); 

// [..] 

context.buildConstraintViolationWithTemplate("that detail is wrong") 
     .addPropertyNode("street") 
     .addConstraintViolation();