Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  75] [ 6]  / answers: 1 / hits: 167606  / 13 Years ago, mon, september 12, 2011, 12:00:00

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.


More From » regex

 Answers
14

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}1d{4}$/

22-03-1981.match(dateReg) // matches
22.03-1981.match(dateReg) // does not match
22.03.1981.match(dateReg) // matches

[#90146] Friday, September 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jalyn

Total Points: 173
Total Questions: 96
Total Answers: 90

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;