Checking numbers, brackets and spaces only when checking jQuery

I try and fail to verify the phone number as part of jQuery validation. All I want is to allow a number like (01660) 888999 . Looking around the net, I find a million examples, but nothing works. Here is my current effort

 $.validator.addMethod("phonenumber", function(value) { var re = new RegExp("/[\d\s()+-]/g"); return re.test(value); //return value.match("/[\d\s]*$"); }, "Please enter a valid phone number"); 
+4
source share
3 answers

Bergi is correct that the way you build a regular expression is incorrect.

Another problem is that you are missing the anchors and + :

 var re = /^[\d\s()+-]+$/; 

Please note that the regex-based solution will still allow some inputs that are not valid phone numbers. You can improve your regular expression in many ways, for example, you can require that, for example, there are at least x digits.

There are many rules for which phone numbers are valid and invalid. It is unlikely that you could encode all of these rules in regular expression in a supported way so that you could try one of these approaches:

  • Find a library capable of checking phone numbers (but maybe not based on regular expressions).
  • If you need a regular expression, use a goal close to the rules, but don't try to handle all special cases. I would suggest trying to write an expression that accepts all valid phone numbers, but does not necessarily reject all invalid phone numbers.

You may also consider writing test cases for your solution. Tests will also be doubled as a form of documentation, which inputs you want to accept and reject.

+5
source

For the RegExp constructor, you need to use a regular expression literal or ::

 var re = /[\d\s()+-]/g; // or var re = new RegExp("[\\d\\s()+-]", "g"); 

See also Creating a regular expression .

In addition, you will need to use the beginning and end line bindings to make sure the regular expression matches the entire line, not just part of it, as well as the repeat modifier , to allow more than one character:

 var re = /^[\d\s()+-]+$/g; 
+2
source

Another approach could be:

 function(value) { return /^\d+$/.test(value.replace(/[()\s+-]/g,'')); } 

and if you also want to check the length of the number, say that it should be a string with 10 digits:

 function(value) { return /^\d{10}$/.test(value.replace(/[()\s+-]/g,'')); } 
+1
source

All Articles