How to validate date in the format "MM/dd/yyyy" in Spring Boot?
22,449
Solution 1
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;
Solution 2
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
Solution 3
@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;
}
}
}
Author by
Saravanan
I am Saravanan MCA Graduate.I am working as a Senior Developer in java environment. Email:[email protected]
Updated on October 05, 2021Comments
-
Saravanan over 2 years
I need to validate the given date has valid month, date and year. Basically, date format would be
MM/dd/yyyy
. But date coming like13/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;
-
Saravanan over 5 yearsIn this case how to show our custom error message for invalid dates..?
-
veben over 5 years@Saravanan, you can use typeMismatch, but it's not ideal. See jtuts.com/2014/11/09/validating-dates-in-spring-form-objects
-
Saravanan over 5 yearsI tried your approach.. but it is showing @CustomDateValidator is not an annotation type.
-
G.Noulas over 5 yearscheck here for details baeldung.com/spring-mvc-custom-validator
-
Rishabh Agarwal over 2 yearsThis is perfect