Validate a number between 10 and 11 characters in length
I am using javascript (and PHP) to validate a simple form with a phone number field. I have it working fine checking that the field has only 10 characters, but I really want to check if the field has between 10 and 11 characters.
Reason being, some people type numbers like so: 1 555 555 5555 and some people do this 555 555 5555.
Here is what I have that works for checking if the length is 10:
if (!(stripped.length == 10)) {
alert("Please enter a valid US phone number.")
return false开发者_JAVA技巧
}
The simple answer is to add a check in your if:
if (!(stripped.length == 10 || stripped.length == 11)) { ... }
Well to do what you're asking:
if (stripped.length != 10 && stripped.length != 11) {
alert("Please enter a valid US phone number.")
return false
}
Still, you may consider using regular expressions to validate phone numbers as they can easily validate a large number of conditions.
Borrowing from RegEx Buddy (which I strongly recommend as it will help you dissect and understand regular expressions):
var phoneRegex = /\(?\b[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}\b/;
var phone = '3334445555';
if(!phone.match(phoneRegex)){
alert('please enter a valid phone number');
}
Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
EDIT
@pawel makes a good point. The best way to validate is to strip out all characters other than digits first. Then ensure you have the correct number of digits, then save that stripped, uniform number to the server. The regex is ideal only for finding valid phone numbers that are hiding in a bigger block of text. It really isn't a smart choice for this...oops :)
Well you probably really want either 10 characters, or a 1, followed by 10 characters.
if (!(stripped.length === 10 || stripped.length === 11 && stripped.charAt(0) === "1")) {
// invalid...
}
I figured it out, just a quick refresh on JS 101 was needed. I actually tried to use the OR || operator but did it like this 10||11
which did not work.
This works:
if (!(stripped.length == 10 || stripped.length == 11)) {
alert("Please enter a valid US phone number.")
return false
}
精彩评论