Possible Duplicate:
A comprehensive regex开发者_运维问答 for phone number validation
Perhaps a forgiving JavaScript solution would only make sure that only valid characters are allowed. (digits, dashes, periods, letters for extension.
Although loop seems best, is there a simple regular expression that checks for valid characters?
Your regex: \d|\.|\-
Although technically you want the opposite [^\d\.\-]
so you can do a replace ->
$('input').blur(function() {
var value = $(this).val();
$(this).val(value.replace(/[^\d\.\-]/g, ''));
});
See fiddle in action - http://jsfiddle.net/GspT4/
A regular expression is just javascript, not jQuery. What is the format you seek? How many letters are allowed in the extension? I could look it up, but it would help greatly if you would do that. It seems numbers from 7 to 11 digits are allowed.
It is nice to allow users to enter phone numbers in block of 3 or 4 characters because it is much easier for them to read, like:
914-499-1900
or
914 499 1900
or similar. Trim the spaces for validation or storage if you like.
For the above formats exactly:
function testPhoneNumber(phoneNumber) {
var re = /^\d{3}[- ]?\d{3}[- ]?\d{4}$/;
return re.test(phoneNumber);
}
Or you can remove unnecessary but allowed characters and test what remains:
function testPhoneNumber(phoneNumber) {
var re = /^\d{10}$/;
return re.test(phoneNumber.replace(/[ -+]/g,''));
}
But these don't allow for extension. If you provide the format, the regular expression part is easy.
精彩评论