How to validate Date type with Springboot validation bean?

Asked

Viewed 91 times

-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!

1 answer

0


After many attempts I discovered the reason for not passing the validator, my entity was annotated with validators of the javax.validation.constraints but, my validator created with the annotations of jakarta.validation.constraints, for this reason, the validator did not work. I put everything as javax.validation.constraints, and now it works!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.