views:

64

answers:

6

I have a regexp which checks if a value has at least 10 digits:

if (foo.match(/^\d{10,}$/))
{
 // At least 10 digits
}

However I want to divide the validation in 2 steps, so first i check if foo has got only numbers, and no other characters, and then i check if its got at least 10 digits.

I can check the 10 digits part using foo.length, but how do i change the regexp above to check if foo has got only numbers. Any ideas?

+3  A: 

You're already checking that it has only numbers. You specify that the pattern must match string start ^, followed by at least ten digits, followed immediately by string end $

Sneak any non-digit in there, and the pattern won't match

That means if you want to divide your test into two steps, for, say having two different error messages, you can check for length first, and then still use that regexp pattern.

David Hedlund
+1 same as my deleted comment
RC
I don't want to check the length first, i want to check if its numeric or not first. Please read the question before answering
Click Upvote
A: 
if (foo.match(/^\d+$/)) {
//all digits
  if(foo.length == 10) {
    //all digits + 10 lenght
    //do whatever
  }
} else {
  //issue error message
}

This is one way. Although I don't understand why you would need to do that. Your own regex already assures that is is 10 characters long AND that these 10 characters can't be anything else then numbers

jitter
Split the check to issue a different error message if the input has non-digits.
mobrule
+2  A: 

One solution: change the qualification from "10 or more" to "one or more", thusly:

if (foo.match(/^\d+$/))
{
 // At least 1 digit
}

If the empty string is acceptable, use * instead of + to match "zero or more."

qid
A: 
var containsOnlyNumbers = /^\d+$/.test(foo);
Darin Dimitrov
A: 

Fail if

foo.match(/\D/)
mobrule
A: 
// Invalid: A non-digit is present
if ( foo.match(/\D/) ) {
   console.warn("Only numbers accepted");
}
// Invalid: foo is all digits, but less than 10 digits
else if ( foo.length < 10 ) {
    console.warn("Minimum 10 digits required");
}
// foo is valid
else {
    console.info("Great success");
}
Justin Johnson