简体   繁体   English

模型注释可以验证两个字段吗

[英]Can a model annotation validate two fields

I have this model class 我有这个模特班

@Document(collection = "MyClass")
public class MyClass implements Persistable<UUID> {

    @NotEmpty(groups = { Create.class})
    private String field1;

    @NotEmpty(groups = { Create.class})
    private String field2;
}

Now during Create, I want to check that either field1 is empty or field2 is but both should not be empty 现在在创建过程中,我要检查field1是否为空或field2为但都不应该为空

Can I do this through preexisting annotations or custom annotations (that implement ConstraintValidator) or will I have to resort to validating in my service layer 我可以通过预先存在的注释或自定义注释(实现ConstraintValidator)来做到这一点,还是必须在服务层中进行验证

You can create a custom annotation and use that annotation to validate in the Create class. 您可以创建一个自定义注释,并使用该注释在Create类中进行验证。

@CustomAnnotation(field1 = "field1", field2 = "field2")
class Create  {

    private String field1;
    private String field2;
}

Custom Annotation: 自定义注释:

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomAnnotationValidator.class)
@Documented
public @interface CustomAnnotation {
    String message() default "One of field1 or field2 required";  //can make use of properties file to interpolate message

    String field1();    
    String field2();

}

then in the validator impl: 然后在验证器中隐含:

public class CustomAnnotationValidator implements ConstraintValidator<CustomAnnotation, Object> {

private String field1Holder;
private String field2Holder;

@Override
public void initialize(CustomAnnotation constraintAnnotation) {
    field1Holder = constraintAnnotation.field1();
    field2Holder = constraintAnnotation.field2();
}

@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
    try {
        final String field1 = BeanUtils.getProperty(value, field1Holder);
        final String field2 = BeanUtils.getProperty(value, field2Holder);
        return !(field1 == null && field2 == null); //your validation logic
    } catch (Exception e) {
        log.error("Error validating object", e);
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM