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");
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With