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开发者_运维技巧?
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.
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."
var containsOnlyNumbers = /^\d+$/.test(foo);
Fail if
foo.match(/\D/)
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
// 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");
}
精彩评论