0

I found a blog post which shows a method of creating validation for an international phone number. The code supplied is:

jQuery.validator.addMethod('intlphone', 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');

I believe it used to work for me but something has changed - possibly a newer version of jQuery - and I'm getting this error:

Uncaught SyntaxError: Invalid regular expression: /^((+)?[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]+))?$/: Nothing to repeat 

I created a JSBin with the items i'm working with, but I'm not having any luck getting rid of the error.

How can I fix old javascript to validate an international phone number with jQuery Validate?

ps: I believe I've tried running this with previous versions of jQuery and I'm still getting the error. I'm not sure what changed.

Ended up using this:

jQuery.validator.addMethod('intlphone', 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');
cwd
  • 53,018
  • 53
  • 161
  • 198
  • 1
    It has a couple unescaped `-` maybe that's the problem. Try with: `/^((\+)?[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]+))?$/` – elclanrs Sep 20 '12 at 23:51

1 Answers1

0

As stated here A comprehensive regex for phone number validation

It will be a lot easier to strip the non-digit characters and create a regex to match only the numbers and extension.

Add this to the beginning of your function to remove all non-digits other than x: value.replace("[^\d+x]", "").match ....

Community
  • 1
  • 1
Ryan Erickson
  • 731
  • 1
  • 15
  • 23