-1
Gentlemen, I would like to know from you, how are you validating Date type fields in Spring-boot with Bean Validation?
I used the note @DateTimeFormat
but I did not get the expected return, and the property did not exist message
to customize the return message.
I even created my own validator, as below:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateValidator.class)
public @interface DateValidation {
String message() default "A data informada é inválida!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String value() default "";
}
public class DateValidator implements ConstraintValidator<DateValidation, Date> {
@Override
public boolean isValid(Date value, ConstraintValidatorContext context) {
if (value == null || (DateUtil.isValidDate(value, "dd/MM/yyyy") && DateUtil.isValidSQLServerDate(value))) {
return true;
}
return false;
}
}
public static boolean isValidDate(Date date, String dateFormat) {
try {
String strDate = parseToString(date, dateFormat);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat).withResolverStyle(ResolverStyle.STRICT);
LocalDate localDate = LocalDate.parse(strDate, dateTimeFormatter);
} catch (DateTimeParseException e) {
return false;
}
return true;
}
public static boolean isValidSQLServerDate(Date dateToCheck) {
Calendar cal = Calendar.getInstance();
cal.set(1753, 0, 1); // 01-Jan-1753
Date dataInicio = cal.getTime();
cal.set(9999, 11, 31); //31-Dez-9999
Date dataFim = cal.getTime();
if (dateToCheck.compareTo(dataInicio) >= 0 && dateToCheck.compareTo(dataFim) <= 0) {
return true;
}
return false;
}
But the validation of spring does not even pass here. Follow the controler:
@PostMapping(consumes = "application/json", produces = "application/json")
public ResponseEntity<InstrumentoAcesso> incluirInstrumentoAcesso(@RequestBody @Valid InstrumentoAcesso instrumentoAcesso, @RequestHeader(name = "Authorization") String token) {
return this.service.create(instrumentoAcesso, this.prepararRequest(token));
}
I would like some light on that, a video, tutorial, information, anything that helps.
Thanks in advance!