I tried to validate the date using custom validation in spring boot. But the only yyyy
is not validating the year although dd
and MM
is working fine.
For Example,
if in RequestBody I passed the date format as
02/1k/2022
, is validated properly and also k2/12/2022
is validated properly but
when I passed a date like 02/12/2k22
is not validated.
I couldn't figure out it.
SpringBoot version: 2.3.0.RELEASE
Dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Code:
public class IsValidDateFormatValidator implements ConstraintValidator<IsValidDateFormat, String> {
@Override
public void initialize(IsValidDateFormat arg0) {
// TODO Auto-generated method stub
}
@Override
public boolean isValid(String arg0, ConstraintValidatorContext arg1) {
if (arg0 != null) {
if (arg0.trim().length() > 10) {
return false;
}
if (!arg0.isEmpty()) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(false);
try {
sdf.parse(arg0);
} catch (ParseException e) {
return false;
}
}
}
return true;
}
}
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {IsValidDateFormatValidator.class})
@Documented
public @interface IsValidDateFormat {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Model:
@NotEmpty(message = "dob {emptyDateValidationMsg}")
@IsValidDateFormat(message = "dob {dateFormatValidationMsg}")
@JsonProperty("dob")
private String dob;
Please suggest what mistake I made...
The same code was validating the year properly if I passed dateformat yyyy-MM-dd instead of dd/MM/yyyy
CodePudding user response:
There is some flaws if you use SimpleDateFormat.parse, that "The method may not use the entire text of the given string". You can find that in javadoc DateFormat
I suggest you can use DateTimeFormatter & LocalDate.parse instead.
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate.parse(arg0, formatter);
} catch (DateTimeParseException e) {
return false;
}