I'm trying to validate different date formats using regex, the formats that are valid are:
YYYY/MM/DD
DD/MM/YYYY
MM-DD-YYYY
I have made this regex so far, but it doesn't validate them all:
^([0-9]{2,4})\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])
CodePudding user response:
I would just keep it simple and use an alternation here:
^(?:\d{4}/\d{2}/\d{2}|\d{2}/\d{2}/\d{4}|\d{2}-\d{2}-\d{4})$
Demo
However, if there be some PHP library which can convert strings to bona fide dates, and validate along the way, then you should look into using that first. Both of our regex patterns would still validate bogus dates such as 2022-02-31
.