2012-07-29 98 views
0

如果我们构建自定义JSR 303验证程序,是否有任何方法,我们可以将字段值传递给验证程序而不是字段名称?基于值的交叉字段验证

下面是我在做什么..

我需要建立这验证这种情况下的自定义类级别的验证..

有两个字段一个& B,其中B是一个日期字段。如果A的值为1,请验证B不为空,其值为未来日期。

现在我能够在this后发布这些要求的验证。在FutureDateValidator的isValid()方法中,我检查了A的值是否为1,然后检查了日期有效性。

@CustomFutureDate(第一= “dateOption”,第二= “日期”,邮件= “这必须为将来的日期”。)

现在我有新的字段集C和d的,其中d是再次日期字段。这次如果C的值是2,我需要验证D是未来的日期。在这种情况下,我不能使用我已经实现的验证器,因为它的第一个字段的值是硬编码的。那么如何解决这个问题,以便为这两种情况重用相同的验证器。

回答

0

为了不硬编码值1/2使它可定制:

@CustomFutureDate(first = "dateOption", firstValue = "1", second = "date", message = "This must be a future date.") 

为了使它工作,你需要修改@CustomFutureDate注释:

public @interface CustomFutureDate { 
    String first(); 
    String firstValue(); 
    ... 
} 

和实施:

public class CustomFutureDateValidator implements ConstraintValidator<CustomFutureDate, Object> { 
    private String firstFieldName; 
    private String firstFieldValue; 
    ... 

    @Override 
    public void initialize(final CustomFutureDate constraintAnnotation) { 
     firstFieldName = constraintAnnotation.first(); 
     firstFieldValue = constraintAnnotation.firstValue(); 
     ... 
    } 

    @Override 
    public boolean isValid(final Object value, final ConstraintValidatorContext context) { 
     // use firstFieldValue member 
     ... 
    } 
} 
+0

谢谢PHP的编码器。因为过去几天我没有上班,所以我没有这样做。肯定会利用它。再次感谢! – RKodakandla 2012-08-02 14:16:39