I need to validate the given date has valid month, date and year. Basically, date format would be MM/dd/yyyy
. But date coming like 13/40/2018
then I need to throw an error message like:
invalid start date
Is there any annotation available in spring to get this done?
@NotNull(message = ExceptionConstants.INVALID_START_DATE)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "MM/dd/yyyy")
private Date startDate;
This annotation has an attribute called pattern that allows you to set a the pattern to validate against. Example usage of the annotation: public class PostForm { @DateTimeFormat(pattern = "yyyy-MM-dd") @NotNull(message = "Please provide a date.") private Date date; private String contents; // getters and setters... }
Validate Using DateFormat Next, let's write the unit test for this class: DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));
You can use a custom deserializer :
public class DateDeSerializer extends StdDeserializer<Date> {
public DateDeSerializer() {
super(Date.class);
}
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String value = p.readValueAs(String.class);
try {
return new SimpleDateFormat("MM/dd/yyyy").parse(value);
} catch (DateTimeParseException e) {
//throw an error
}
}
}
and use like :
@JsonDeserialize(using = DateDeSerializer .class)
private Date startDate;
You can use something like that:
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@JsonFormat(pattern = "MM/dd/yyyy")
private LocalDate startDate;
But I don't know if it can work with class Date
@CustomDateValidator
private LocalDate startDate;
@Documented
@Constraint(validatedBy = CustomDateValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomDateConstraint {
String message() default "Invalid date format";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class CustomDateValidator implements
ConstraintValidator<CustomDateConstraint, LocalDate> {
private static final String DATE_PATTERN = "MM/dd/yyyy";
@Override
public void initialize(CustomDateConstraint customDate) {
}
@Override
public boolean isValid(LocalDate customDateField,
ConstraintValidatorContext cxt) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
try
{
sdf.setLenient(false);
Date d = sdf.parse(customDateField);
return true;
}
catch (ParseException e)
{
return false;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With