jQuery international phone number validaiton method for jquery.validate.js

The validate plugin for jQuery by Jörn Zaefferer is the best form validation tool I have used. It is very simple to set up and offers many built in functions. Furthermore error message insertion is clean and easy to follow. One thing I found that was missing from the default set of rules was a rule for validating international phone numbers. I understand why it was not included, because it can be difficult to verify so many possible variations. However I have written a fairly loose validator that should work for most cases and keep out completely wrong data.

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.


Anonymous said...

thank you ! you helped me much !

Anonymous said...

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:)');

Anonymous said...

@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.

Karl Horky said...
This comment has been removed by the author.
Karl Horky said...

@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:

Curtis said...

Thanks for this. I'm horrible with regex so you've saved me some time.

Danish Backer said...

thanks a TON! :)

Post a Comment