I am trying to build a regular expression which checks the date if it is in the following formats (11-2-07, 1-25-2007, or 01/25/2007). My regular expression looks like this:
/^([\d{2}\d{1}])([\-\/])([\d{2}\d{1}])(\-\/)([\d{2}\d{4}])$/
when I enter dates in the dates in the required format the method test() actually returns false. Can you please help me find the mistake ?
Try this one:
var re = /^([0123]?[\d])([\-\/])([0123]?[\d])([\-\/])((19|20)?\d\d)$/;
0, 1, 2 or 3. If you know exact date format you can remove 3 from month group, or use (0?[1-9]|1[012]) for month group and (0?[1-9]|[12][0-9]|3[01]) for day group.19 or 20.var re = /^([0123]?[\d])([\-\/])([0123]?[\d])([\-\/])((19|20)?\d\d)$/;
console.log('01-02-1999', re.test('01-02-1999'));
console.log('01/02/1999', re.test('01/02/1999'));
console.log('41-02-1999', re.test('41-02-1999'));
console.log('01/42/1999', re.test('01/42/1999'));
You can select 1 or 2 digit occurrences with \d{1,2}.
There are missing square brackets in the last hypen / forward slash group.
And the last group should be (\d{2}|\d{4}).
No need to escape the forward slash inside the character classes.
/^(\d{1,2})([\-/])(\d{1,2})([\-/])(\d{2}|\d{4})$/
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