match exactly 4 numbers

J

jimmygoogle

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;
}

}
 
D

Darko

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 <input> tag,
thus avoiding one part of the unpleasant alert-boxes.

Darko
 
L

Lee

jimmygoogle said:
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}/;

That will match any entry that contains 4 consecutive digits, no matter
what other characters there may be.
You want to match the beginning of the string is followed by
exactly 4 digits, followed by the end of the string:

var regexp = /^\d{4}$/;


--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,125
Latest member
VinayKumar Nevatia_
Top