Eduard Luca Eduard Luca - 1 year ago 128
Javascript Question

Javascript - Regex to validate date format

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download