I am validating an entity with a hibernate validator in a spring boot project. I got an exception for the Date validator @Past . I faced javax.validation.ValidationException: HV000028: Unexpected exception during isValid call
This is the dependency I have in my gradle.build file
implementation 'org.springframework.boot:spring-boot-starter-validation'
The following my a similar entity I have
@NoArgsConstructor
@Data
public class Person{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "FIRST_NAME")
@NotEmpty(message = "ENTER REQUIRED FIELDS - FIRST NAME")
private String firstName;
@Column(name = "LAST_NAME")
@NotEmpty(message = "ENTER REQUIRED FIELDS - LAST NAME")
private String lastName;
@Column(name = "BIRTH_DATE")
@Past(message = "PLEASE ENTER A VALID DATE ")
private Date birthDate;
}
This is a log trace
2020-10-25 13:09:11.421 DEBUG 21952 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed 500 INTERNAL_SERVER_ERROR```
I Quickly ran on my sample project where everything was already configured i think that Date format is the issue. Available default formats are
Here is how i have done it
Controller
@PostMapping(value = "test-person")
public TestPerson testPerson(@Valid @RequestBody TestPerson testPerson) {
return testPerson;
}
@Getter
@Setter
@NoArgsConstructor
@Data
public static class TestPerson {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "FIRST_NAME")
@NotEmpty(message = "ENTER REQUIRED FIELDS - FIRST NAME")
private String firstName;
@Column(name = "LAST_NAME")
@NotEmpty(message = "ENTER REQUIRED FIELDS - LAST NAME")
private String lastName;
@Column(name = "BIRTH_DATE")
@Past(message = "PLEASE ENTER A VALID DATE ")
@NotNull
private Date birthDate;
}
@ControllerAdvice
public static class RestExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleAllExceptionMethod(MethodArgumentNotValidException ex, WebRequest requset) {
// general response dump
return ResponseEntity.badRequest().body(ex.getBindingResult().getAllErrors());
}
}
Also make sure that for birthDate
you should not use @NotEmpty
instead use @NotNull
because for NotEmpty
length of character sequence is evaluated
This is for anyone having the same issue as mine. My issue was the Date objects were from java.sql.Date. I changed them to java.util.Date now the validation works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.