views:

57

answers:

1

Hi.

I'm a bit confused about different regex formats.

The following methods are causing an error.

function validateDate(str)  {
    var expr = /^((((0?[1-9]|[12]\d|3[01])[\/](0?[13578]|1[02])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\/](0?[13456789]|1[012])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\/]0?2[\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\/]0?2[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/;
    return validate(expr, str);
}

function validateTime(str)  {
    var expr = /^([0-1]?[0-9]|[2]?[0-3])\:([0-5][0-9])$/;
    return validate(expr, str);
}

function validate(pattern, str) {
    return str.match(pattern);
}

I've taken the following regex's from the web. I think the problem is regarding certain escape characters

What's wrong here?

Thanks : )

+3  A: 

In the validateDate function you are assigning the regular expression object to the exp variable, but in the next line you are using the expr variable, which is undefined.

Edit:

What do you expect the functions to return? Right now they are returning an array of matches. If you want them to just return true or false, you might want to use the test method instead:

function validate(pattern, str) {
  return pattern.test(str);
}
Guffa
done. But that's not all. There's still something wrong. I've replaced `\d` with `\\d` .. still no luck.
wretrOvian
Don't replace `\d` with `\\d`, then you will match the two characters backslash and "d" instead of digits. Escaping backslashes is what you do if you have the pattern in a string. What kind of error are you talking about? What happens? Do you get any error message?
Guffa