g3blv
g3blv

Reputation: 4377

Validating date with Spring Boot or Hibernate Validator

I've built a REST Service using Spring Boot. I'm also using Hibernate Validator to validate data. I have a REST endpoint like this:

@PostMapping(value = "${apiVersion.v_1}" + "/parameter-dates")
    public ResponseEntity createParameterDate( @RequestBody ParameterDate parameterDate){
// Some code that use parameterDate
}

ParameterDate is defined in a class like this:

public class ParameterDate {

    @NotNull(message = "Parameter Date Unadjusted can not be blank or null")
    private Date parameterDateUnadjusted;
    @NotNull(message = "Parameter Date Adjusted can not be blank or null")
    private Date parameterDateAdjusted;
    private Date parameterDateAdded;
    private Date parameterDateChanged;    
}

I would like to validate parameterDateUnadjusted and parameterDateAdjusted to make sure both of them are valid dates. I've tried with @DateTimeFormat(pattern = "yyyy-MM-dd") but it won't give me a validation error for not validate as long as they stick to yyyy-MM-dd. One example would be 2017-01-40 that it just interpret as 2017-02-09. I guess @DateTimeFormat is rather a formatter than a validator. I also tried using Hibernate Validator's @Pattern and rexexp like @Pattern(regexp="\\t(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\\d\\d\\t"). But this gives me the error

V000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.util.Date'. Check configuration for 'parameterDateAdjusted'

Any suggestion how I can validate these dates?

Upvotes: 5

Views: 10969

Answers (1)

Jaiwo99
Jaiwo99

Reputation: 10017

Here is an example to implement validator for Date object:

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyDateValidator.class)
@Documented
public @interface ValidDate {

    String message() default "some message here";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

public class MyDateValidator implements ConstraintValidator<ValidDate, Date> {
   public void initialize(ValidDate constraint) {
   }

   public boolean isValid(Date value, ConstraintValidatorContext context) {
      // validate the value here.
   }
}

Upvotes: 5

Related Questions