First of all, you should start using LocalDate
instead of Date
.If you need the date to be converted to a desired format while it is being binded to the model , then you should use a custom JsonDeserializer , more on that: Java 8 LocalDate Jackson format
If you just need to trigger the validation on the date object in the request and the expectation is that the date is not needed to be formatted to desired format at the controller, then you could setup a custom validator like :
@Documented
@Constraint(validatedBy = CustomDataValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDataConstraint {
String message() default "Invalid data";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class CustomDataValidator implements
ConstraintValidator<CustomDataConstraint, String> {
@Override
public void initialize(CustomDataConstraint data) {
}
@Override
public boolean isValid(String field,
ConstraintValidatorContext cxt) {
return field!= null; // Your logic here for validation
}
}
The isValid
method implementation can be customized to whatever logic that you need to validate the date format. Then in your controller model class put the annotation like :
@CustomDataConstraint
@Column(name = "ARRIVAL_DATETIME")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@Temporal(TemporalType.DATE)
private Date arrivaldatetime;
The custom validation annotation will be triggered at the time of model binding automatically by springboot and the validation will happen like JSR303.