To use the validation rule simply add the method to the validate plugin using the code below to a place where it is called before form validation.
$.validator.addMethod('phone', function(value) {
var numbers = value.split(/\d/).length - 1;
return (10 <= numbers && numbers <= 20 && value.match(/^(\+){0,1}(\d|\s|\(|\)){10,20}$/)); }, 'Please enter a valid phone number');
The validator will allow between 9 and 19 digit numbers with a hard character limit between 10 and 20. The special characters allowed are: '(', ')', '+', and ' '. Play around with it to see just what formats are accepted and tweak to your needs.
7 comments:
thank you ! you helped me much !
Thank you for the great start; however, your code was not restrictive enough for me. I am using this regex instead:
$.validator.addMethod('phone', function(value) {
return (value.match(/^((\+){0,1}\d\s)?\(?([0-9]{3})\)?\s*[\. -]?\s*([0-9]{3})\s*[\. -]?\s*([0-9]{4})\s?((ext|x)\s*\.?:?\s*([0-9]+))?$/)); }, 'Please enter a valid phone number (Intl format accepted + ext: or x:)');
@Nate: Nice mod Nate! I prefer the first \s to be \s* so that the whitespace between the int'l identifier is not required, but still supported.
@Nate: Great extension detection. However it appears your code doesn't take into account international phone numbers such as the German phone number +49-89-636-48018. I found Renso Hollhumer's international phone number regular expression at the link below and created this modification of your code:
$.validator.addMethod('phone', function(value) { return (value.match(/^((\+)?[1-9]{1,2})?([-\s\.])?((\(\d{1,4}\))|\d{1,4})(([-\s\.])?[0-9]{1,12}){1,2}(\s*(ext|x)\s*\.?:?\s*([0-9]+))?$/)); }, 'Please enter a valid phone number (Intl format accepted + ext: or x:)');
Renso Hollhumer's Regex for International Phone Number:
http://regexlib.com/REDetails.aspx?regexp_id=3009
Thanks for this. I'm horrible with regex so you've saved me some time.
thanks a TON! :)
Post a Comment