0

Here is my Json data

{
     "arrivaldatetime": "2020-08-21 11:50:09"
}

Below is my Model class

@Column(name = "ARRIVAL_DATETIME")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
@Temporal(TemporalType.DATE)
private Date arrivaldatetime;

How to validate arrivaldatetime ? it should allow only proper date and time format "yyyy-MM-dd HH:mm:ss"

here is sample screenshot of json request which taking wrong date. [1]: https://i.stack.imgur.com/MSRmj.png

Sweety23
  • 21
  • 1
  • 2
  • 7

1 Answers1

2

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.

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39