Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate numbers, parenthesis and spaces only in jQuery validation

I am trying and failing hard in validating a phone number within jQuery validation. All I want is to allow a number like (01660) 888999. Looking around the net I find a million examples but nothing seems to work. 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");
like image 278
Chris Avatar asked Feb 19 '23 15:02

Chris


1 Answers

Bergi is correct that the way you are constructing the regular expression is wrong.

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

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

Note though that a regular expression based solution will still allow some inputs that aren't valid phone numbers. You can improve your regular expression in many ways, for example you might want to require that there are at least x digits, for example.

There are many rules for what phone numbers are valid and invalid. It is unlikely you could encode all those rules into a regular expression in a maintainable way, so you could try one of these approaches:

  • Find a library that is able to validate phone numbers (but possibly not regular expression based).
  • If you need a regular expression, aim for something that is a close approximation to the rules, but doesn't attempt to handle all the special cases. I would suggest trying to write an expression that accepts all valid phone numbers, but doesn't necessarily reject all invalid phone numbers.

You may also want to consider writing test cases for your solution. The tests will also double as a form of documentation of which inputs you wish to accept and reject.

like image 140
Mark Byers Avatar answered Apr 28 '23 08:04

Mark Byers