The following are all valid format for telephone number (note there can be le开发者_如何转开发ading and trailing spaces):
- 555-444-3333
- (555)-(444)-(3333)
- 5554443333
- 5554443333
- 5554443333
- 555 444 3333
- 555 4443333
- 555444 3333
- (5554443333)
- (555-444-3333)
How can I validate using Regex or Javascript in .NET?
I wouldn't use a regular expression directly. I'd copy each character to a new string, while skipping parantheses, hyphens and spaces. Then check that the resulting string has ten characters, all of which are digits.
I don't know about .Net regexes, but ^[0-9]*$ is the way most regex libraries will verify that a string is entirely digits.
Alternatively you can use the standard library isdigit() function to check the characters one-by-one as you scan through them.
Try this
function isPhoneNumber(x) {
return /^[0-9\-\(\)\s]*$/.test(x) && x.replace(/[^0-9]/g,'').length == 10;
}
I share the concerns of some of the commenters but it does what you're asking for.
The first half of the test will fail if the string contains anything else than digits, hyphens, parens or spaces. The second half of the test will fail if the number of digits in the string is not 10.
精彩评论