On Feb 26, 6:23 pm, "jimmygoogle" <jtbutle...@comcast.netwrote:
I am checking user input in a form and they should ennter only the
last 4 digits of their account number. My code catches it if they
enter 3 but it thinks it ok if they enter 5. How can I have it fail
for 5 numbers?
function checkAccount(account) {
var regexp = /\d{4}/;
if (!regexp.test(account)){
alert ('Please enter the last 4 digits of your account number.');
return false;
}
else{
return true;
}
}
Try surrounding your regular expression with '^' and '$' characters.
In classic regular expressions, they mean "start of line" and "end of
line", respectively. In your case, you want to find the four digits in
the test-string, and they are successfully found if the user types 5
digits; what you wanted to say is "I want ONLY four digits", and I
think (haven't tried in JS, though) this can be accomplished by /^
\d{4}$/ Maybe the best way is to put maxlength=4 in your <inputtag,
thus avoiding one part of the unpleasant alert-boxes.
Darko