Home > database >  Java spring date @Pattern allow empty string in DTO
Java spring date @Pattern allow empty string in DTO

Time:06-20

im working on java web project and i want to validate my DTO date field. i used the @Pattern annotation from import javax.validation.constraints.Pattern; and this is my code :

 @Pattern(regexp = "^([0-9]{2}/[0-9]{2}/[0-9]{4})$", message = "Date format should be dd/mm/yyyy")
  private String myDatefield;

this validationworks fine when i send invalid date format. but the issue is that field is not mandatory so i want to tolerate the case when the field is empty :

{
  "myDatefield":""
}

but in this cas i still getting the error "Date format should be dd/mm/yyyy"

do you have an suggestion how i can modify my regx Pattern to validate date format and accept the empty string.

thanks in advance.

CodePudding user response:

Adding ^$ should do the trick.

@Pattern(regexp = "^$|^([0-9]{2}/[0-9]{2}/[0-9]{4})$", message = "Date format should be dd/mm/yyyy")
  private String myDatefield;
  • ^$ provides you the case for an empty string
  • | is the or delimiter for alternative patterns
  • Related