0

If we are build a custom JSR 303 validator, is there any way, we can pass field's value to the validator instead of the field's name?

Here is what I am doing..

I need to build a custom class level validation which validates this case..

There are two fields A & B where B is a date field. If A's value is 1, verify that B is not null and its value is future date.

Now I was able to build a validation with these requirements following this post. In the FutureDateValidator's isValid() method, I have checked whether A's value is 1 or not and then I checked the date validity.

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

Now I have new set of fields C and D, where D is again the date field. This time I need to verify that D is a future date if C's value is 2. In this case I cannot use the validator I already implemented because it has the first field's value hard-coded. So how do I solve this issue to reuse the same validator for these two cases.

Community
  • 1
  • 1
RKodakandla
  • 3,318
  • 13
  • 59
  • 79

1 Answers1

0

To not hardcode values 1/2 made it customizable:

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

To make it work you need to modify @CustomFutureDate annotation:

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

and implementation:

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
        ...
    }
}
Slava Semushin
  • 14,904
  • 7
  • 53
  • 69
  • Thanks php-coder. I didn't try this as I was out of office past few days. Will certainly make use of it. Thanks again! – RKodakandla Aug 02 '12 at 14:16