0

I am trying to implement custom bean validation for java.sql.Timestamp like below -

@Constraint(validatedBy = { DateTimeValidator.class })
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidDateTime {
    String format() default "yyyy-MM-dd HH:mm:ss.S";

    String message() default "{Invalid timestamp}";

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

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

    boolean value() default true; }

Implementation for DateTimeValidator.java

public class DateTimeValidator implements ConstraintValidator<ValidDateTime , Timestamp > {

    private String format;

    @Override
    public void initialize(ValidDateTime  validDateTime ) {
        format = validDateTime.format(); }

    @Override
    public boolean isValid(Timestamp value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) return false;

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            sdf.parse(value.toString());
        } catch (Exception e) { return false; }
        return true; }}

Field on which this annotation is applied -

@ValidDateTime(message="Invalid StartDateTime")
protected Timestamp startDateTime;

This works fine if the input value is of the format "2017-10-21T11:11:11", but if I pass any invalid value like any string(Example : "TEST_DATE") as input instead of date, this validator is not getting invoked and I get JAXB parse exception.

How to correct this implementation to invoke for all input values and validate the correct value?

springenthusiast
  • 403
  • 1
  • 8
  • 30
  • 1
    Thing is that you are applying that custom constraint to already parsed data. So if you want to check the format with a constraint you probably should use a String instead of Timestamp. And in such case it'll probably would be enough to use @Pattern (no need in custom constraint and validator). Otherwise if you are using Timestamp - first data is parsed and converted to a Timestamp - which fails as a 'TEST_DATE' could not be parsed correctly ... – mark_o Oct 03 '17 at 07:57
  • Thank you, I was thinking of String approach but as there are many fields of this type wanted to check if there's any other approach to solve this issue. – springenthusiast Oct 04 '17 at 12:12

0 Answers0