使用Spring验证时进行多个字段(自定义+非空)验证

时间:2019-05-30 11:55:31

标签: java spring bean-validation

我有一个dto这样的人

@FieldMatch(first = "email", second = "emailConfirm", message = "E-posta adresleri eslesmeli")
public class EmailDTO {


    private String email;


    private String emailConfirm;

这是验证者

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {


    private String firstFieldName;
    private String secondFieldName;
    private String message;

    @Override
    public void initialize(final FieldMatch constraintAnnotation) {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
        message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(final Object value, final ConstraintValidatorContext context) {
        boolean valid = true;
        try
        {
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

            valid =  firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);
        }
        catch (final Exception ignore)
        {
            // ignore
        }

        if (!valid){
            context.buildConstraintViolationWithTemplate(message)
                    .addPropertyNode(firstFieldName)
                    .addConstraintViolation()
                    .disableDefaultConstraintViolation();
        }

        return valid;
    }
}

这是界面

arget({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface FieldMatch {


    String message() default "The fields must match";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String first();
    String second();

    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List
    {
        FieldMatch[] value();
    }
}

但是我也想将类更改为此

@FieldMatch(first = "email", second = "emailConfirm", message = "E-posta adresleri eslesmeli")
public class EmailDTO {



     @Max(value = 150, message = "E-posta karakter sayisi fazla!")
        @Email(message = "Email should be valid")
        @NotNull(message = "Name cannot be null")
        @NotEmpty(message = "Name cannot be null")
        private String email;

        @Max(value = 150, message = "E-posta karakter sayisi fazla!")
        @Email(message = "Email should be valid")
        @NotNull(message = "Name cannot be null")
        @NotEmpty(message = "Name cannot be null")
        private String emailConfirm;

我应该使用另一个通用约束还是像上面所示的许多注释?我还拥有其他实体,例如password等,这些实体也将具有相同的验证。

某些字段可以是nullable,因此并非每个字段都必须通过null约束进行检查。我想做一个非常通用的验证。我将发送到前端(thymeleaf),所以我需要查看违反了哪个约束。

电子邮件具有@email批注,不会在密码验证中出现。其他的很常见。喜欢

notnull, notempty, matching, notblank

我找不到很好的例子。我在以下有关该主题的帖子中找到了内容,但是我找不到一个自定义+示例,例如@email验证。

0 个答案:

没有答案