Ali
Ali

Reputation: 267077

Javascript regexp question

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?

Upvotes: 1

Views: 190

Answers (6)

Justin Johnson
Justin Johnson

Reputation: 31300

// 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");
}

Upvotes: 0

jitter
jitter

Reputation: 54605

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

Upvotes: 0

mob
mob

Reputation: 118605

Fail if

foo.match(/\D/)

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

var containsOnlyNumbers = /^\d+$/.test(foo);

Upvotes: 0

qid
qid

Reputation: 1913

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."

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

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.

Upvotes: 3

Related Questions