自定义验证注释失败

时间:2017-12-11 09:04:43

标签: java spring-mvc

创建了一个自定义验证注释,用于检查两个弹簧形式字段是否相等。

PasswordVerification:

@Constraint(validatedBy = PasswordVerificationValidator.class)
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface PasswordVerification {
    String message() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

PasswordVerificationValidator:

public class PasswordVerificationValidator implements ConstraintValidator<PasswordVerification, UserFormRegistration> {

    @Override
    public void initialize(PasswordVerification constraintAnnotation) {}

    @Override
    public boolean isValid(UserFormRegistration userFormRegistration, ConstraintValidatorContext context) {
        return userFormRegistration.getPassword().equals(userFormRegistration.getVerifyPassword());
    }
}

UserFormRegistration:

@PasswordVerification(message = "Password and password confirmation fields don't match")
public class UserFormRegistration {
    private String password;
...

因此,如果注释应用于UserFormRegistration类,它可以正常工作。但是如果我想把它应用到现场(见下文),那就失败了。

public class UserFormRegistration {
    @PasswordVerification(message = "Password and password confirmation fields don't match")
    private String password;
...

例外:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'ua.com.vertex.validators.interfaces.PasswordVerification' validating type 'java.lang.String'. Check configuration for 'password'

如何解决?

1 个答案:

答案 0 :(得分:0)

我想您也想在方法级别应用注释,因此您需要ElementType.METHOD

所以将@Target({ElementType.TYPE, ElementType.FIELD})更改为

@Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})

所以现在@PasswordVerification将适用于方法,类,接口,枚举和字段