enu
enu

Reputation: 2563

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 ?

Upvotes: 3

Views: 108

Answers (2)

Valentin Podkamennyi
Valentin Podkamennyi

Reputation: 7369

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'));

Upvotes: 2

M A
M A

Reputation: 72884

  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})$/
    

Upvotes: 1

Related Questions