Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java spring date @Pattern allow empty string in DTO

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

thanks in advance.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading