Spring MVC验证:为每个验证检查设置特定的错误消息

时间:2014-01-16 01:47:23

标签: java validation spring-mvc annotations bean-validation

我在Spring中使用JSR-303来验证密码字段。我想将所有验证逻辑放在一个类中,并相应地显示每个错误的消息。这可能吗?为每个验证检查创建一个单独的类(即PasswordLengthValidator,PasswordRegexValidator)更好吗?

目前,我只能根据密码界面显示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])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$")) {
            // Message: password should be bla bla
            return false;
        }

        return true;
    }

}

1 个答案:

答案 0 :(得分:1)

您的验证工具可以使用ConstraintValidatorContext API发送验证消息:

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

// [..]

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