Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Regex to validate date format [duplicate]

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.

like image 819
Eduard Luca Avatar asked Sep 12 '11 12:09

Eduard Luca


2 Answers

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 
like image 197
Billy Moon Avatar answered Sep 22 '22 11:09

Billy Moon


Format, days, months and year:

var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;

like image 42
nicoabie Avatar answered Sep 24 '22 11:09

nicoabie