I'm trying to ensure a valid date of birth by making sure it's 4 characters long and every character is a digit.
function validateBirth() {
var year = document.forms["myForm"]["birth_year"].value;
if (year.match(/\A\d{4}\z/) !== null) {
alert("Date of birth must be 4 digits");
return false;
}
}
I'm trying to use JavaScript's string#match
function to search for a regular expression in a value. Here we know that it must contain 4 digits, but that it also must not contain any non-digits.
For example, a string like a4b456
would be invalid. That's why I used the regex tags \A
and \z
for starting and ending a string respectively.
When I test out this function in jsconsole, it looks like this
var year = "1958"
year.match(/\A\d{4}\z/)
=> null
I tested the exact same regex in rubular and learned that there was a match. Am I getting crazy, or is there something here I'm missing?
I know I can do this using HTML Input Validation
, but that won't work on non-modern browsers so I need to use the JavaScript method.
Start and end of a string for a JavaScript regex are ^
and $
respectively. (\A
and \z
are valid for start and end in Ruby, but not JavaScript.) So this regex will work:
year.match(/^\d{4}$/);
If you're interested in a Boolean result rather than receiving the actual match, you can do this instead:
/^\d{4}$/.test(year)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments