Is there any way to have a regex in JavaScript that validates dates of multiple formats, like: DD-MM-YYYY or DD.MM.YYYY or DD/MM/YYYY etc? I need all these in one regex and I'm not really good with it. So far I've come up with this: var dateReg = /^\d{2}-\d{2}-\d{4}$/;
for DD-MM-YYYY. I only need to validate the date format, not the date itself.
You could use a character class ([./-]
) so that the seperators can be any of the defined characters
var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/
Or better still, match the character class for the first seperator, then capture that as a group ([./-])
and use a reference to the captured group \1
to match the second seperator, which will ensure that both seperators are the same:
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/ "22-03-1981".match(dateReg) // matches "22.03-1981".match(dateReg) // does not match "22.03.1981".match(dateReg) // matches
Format, days, months and year:
var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With