1

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?

0

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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

Comments

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

Comments

0

Fail if

foo.match(/\D/)

Comments

0
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

1 Comment

Split the check to issue a different error message if the input has non-digits.
0
// 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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.