1

I am trying to use a javascript regular expression to validate date of birth textbox. here is my code

var patt=/[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}/;
alert(patt.test("1985/08/03"));

and the error said: SyntaxEror: Unexpected token {

I don't understand why, this pattern works fine in the asp.net RegularExpressionValidator controller. Many thanks

pita
  • 537
  • 4
  • 15
  • 35
  • I hope you are not doing anything international or at least specyfying the desired format, because otherwise a date might be '2012-11-13' or '20.10.2012' or some such. – Eugene Ryabtsev May 28 '12 at 13:13
  • i used a datepicker and the format is fixed, but i assume some people will type something in, so I use RE to validate – pita May 28 '12 at 13:15

4 Answers4

4

You need to escape the / characters, otherwise the interpreter sees the first one and thinks that's the end of the regexp.

You should also put anchors in your regexp to ensure it matches the whole string, and doesn't match any string which happens to contain that pattern.

For brevity you can use \d instead of [0-9], too:

var patt = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

NB: your sample doesn't work - you've put the year first, but the RE is expecting it to be last.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

Here a sample code that really validate a date in JavaScript :

function isValidDate(dateStr) {
    s = dateStr.split('/');
    d = new Date(+s[2], s[1]-1, +s[0]);
    if (Object.prototype.toString.call(d) === "[object Date]") {
        if (!isNaN(d.getTime()) && d.getDate() == s[0] && 
            d.getMonth() == (s[1] - 1)) {
            return true;
        }
    }
    return false;
}

See Detecting an "invalid date" Date instance in JavaScript

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

The problem is that you are not escaping the / separators in the pattern. Try

/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/;
Morgan ARR Allen
  • 10,556
  • 3
  • 35
  • 33
0

The regex (after you fix the non-escaped '/') will only check for the right number of digits.
It will not check if the month is between 1 and 12, the days between 1 and 31, or 30, or 28, or 29 depending on the month and leap years.

If that's enough for you, the closest you can get with regex is (assuming dd/mm/yyyy):

/(3[01]|[12][0-9]|0?[1-9])\/(1[012]|0?[1-9])\/([12][0-9]{3})/

Days will be in the range 1-31
Month will be in the range 1-12
I took the liberty to restrict the years from 1000 to 2999, but you can catch the format, if you want to restrict from 1970 to 2059 use (19[789][0-9]|20[0-5][0-9]) on the year part.
And you'll get the day on $1, the month on $2 and the year on $3 (I think)

ilomambo
  • 8,290
  • 12
  • 57
  • 106