2

I am trying to validate whether user is entering mobile number correctly. For this I have written the following regex which seems to be buggy. Mobile number can Optionally start with + can have Optional spaces, round brackets, hyphens ( - ). It cannot contain any alphabets or any other character.

jQuery.validator.addMethod("mobileNumber", function(value,element) {
            return this.optional(element) ||  /(?:([+]))?[0-9]*/.test(value);
}, "Please enter a valid Contact Number");

Following inputs should match,

+1-222

(+1) 222

+1222

2222

02-222

But these shouldn't match.

1+222

AAA

AA12

2.2.2

How should I write the regex for above criteria?

Thanks.

Shrey
  • 2,374
  • 3
  • 21
  • 24
  • Take a look [here][1]. This may be helpful [1]: http://stackoverflow.com/a/123681/2266001 – Yassine OUAAMOU May 15 '13 at 14:59
  • What's wrong with the Mobile Phone Number rules already built into this plugin's `additional-methods.js` file? See: http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – Sparky May 15 '13 at 15:47
  • I didn't know about that such rule exists.. does it satisfy the above criteria ? – Shrey May 15 '13 at 18:02
  • Just take a peek to find out: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js – Sparky May 16 '13 at 03:58
  • Thnxx.. I saw it..But US & UK formats wont suite me.. It's little more strict than I currently need. – Shrey May 16 '13 at 09:42

2 Answers2

3

Try the following:

^(\+|\(\+)?\d+(\-|\)|\s)+?\d+

See it working here: http://regexr.com?34sm1

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0
// true
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('+1-222');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('(+1)222');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('+1222');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('01-2222');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('86-2222');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('2222');

// false
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('1+2342');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('+123-222');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('AAA');
/^(\+[0-9]{1,2}\-|\(\+[0-9]{1,2}\)|\+[0-9]{1,2}|[0-9]{2}\-|)[0-9]+$/.test('6786-2342');
Phoenix
  • 756
  • 1
  • 7
  • 22