Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date validation with regular expression

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 ?

like image 802
enu Avatar asked Jul 09 '26 13:07

enu


2 Answers

Try this one:

var re = /^([0123]?[\d])([\-\/])([0123]?[\d])([\-\/])((19|20)?\d\d)$/;
  1. First and third groups match day and month which can start only from 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.
  2. Second and fourth groups match hyphen and slash separators.
  3. And the last one group matches the year which starts from 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'));
like image 79
Valentin Podkamennyi Avatar answered Jul 11 '26 03:07

Valentin Podkamennyi


  1. You can select 1 or 2 digit occurrences with \d{1,2}.

  2. There are missing square brackets in the last hypen / forward slash group.

  3. And the last group should be (\d{2}|\d{4}).

  4. No need to escape the forward slash inside the character classes.

    /^(\d{1,2})([\-/])(\d{1,2})([\-/])(\d{2}|\d{4})$/
    
like image 45
M A Avatar answered Jul 11 '26 02:07

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!