0

I am writing a birthday validation form with JavaScript but it doesn't work properly. For example, 40/40/2012 is invalid but it doesn't give any alert.

JavaScript

function onFormSubmit(form_element) {

    var birthday = form_element.birthday.value;
    if ( !/\d{2}\/\d{2}\/\d{4}/.test(form_element.birthday.value) )
    {
        alert("This field is required. Please enter date mm/dd/yyyy!");
        return false;
    }
    return true;
}

HTML

<form onsubmit="return onFormSubmit(this)">
    Birthday:<input type="text" name="birthday" /><br />
    <input type="submit" value="submit" />
</form>
halfer
  • 19,824
  • 17
  • 99
  • 186
user1332075
  • 63
  • 3
  • 10
  • You could adapt this: http://stackoverflow.com/a/276511/525649 – Adam Apr 15 '12 at 13:04
  • That regular expression makes it pretty clear why you don't get an alert. If you didn't write that yourself, find a good tutorial on regular expressions. – erturne Apr 15 '12 at 13:09

1 Answers1

2

What I like to do is this:

var birthday = form_element.birthday.value;
var match = /^(\d\d)\/(\d\d)\/(\d\d\d\d)$/.exec(birthday);
if (!match || match.length < 4) return false;

var d = new Date(match[3] - 0, (match[2] - 0) - 1, match[1] - 0);
if (d.getFullYear() != match[3] || d.getMonth() + 1 != match[2] || d.getDate() != match[1])
  return false;

return true;

If you make a date from a valid year/month/day, and then check those values on the Date object, you should get the same values back. If you don't then that means the Date object adjusted the bogus values to represent a valid date, which means that the bogus values were, well, bogus.

edit — sorry my code is written for day/month/year; if you want month/day/year, swap match[2] and match[1] in the above.

Pointy
  • 405,095
  • 59
  • 585
  • 614