Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex - What to use to validate a phone number?

Could anyone tell me what RegEx would work to validate an international phone number including white space between the numbers and also allowing for these chars: - ( ).

The amount of numbers in the string is not too important, I would just like the user to be able to type something like either example 1 or 2 if they wish:

Example:

  1. +44 (0) 207 111 1111

  2. 442071111111

I have already read through and tested the posted answers to some similar questions to the best of my understanding but so far none of them are working for me the way I want them to.

Please can someone help me out with a clear explanation of how the above should be written for validation?

Many thanks to anyone who can help.

like image 797
user2031340 Avatar asked Feb 01 '13 04:02

user2031340


2 Answers

Try this code

HTML Code

<input type="text" id="phone"/>

JS Code

$("#phone").blur(function() {
  var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/
  var no = $("#phone").val();
  if (!regexp.test(no) && no.length < 0) {
    alert("Wrong phone no");
  }
});
like image 114
Sagar Hirapara Avatar answered Oct 09 '22 21:10

Sagar Hirapara


This is a long regex, but it supports both formats (for example 2 to be a valid international number, is MUST start with either + or 00):

/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i

This allows extensions and a multiple choice of formats and separators.

Matches:

  • (+351) 282 43 50 50
  • 90191919908
  • 555-8909
  • 001 6867684
  • 001 6867684x1
  • 1 (234) 567-8901
  • 1-234-567-8901 x1234
  • 1-234-567-8901 ext1234
  • 1-234 567.89/01 ext.1234
  • 1(234)5678901x1234
  • (123)8575973
  • (0055)(123)8575973

On $n, it saves:

  1. Country indicator
  2. Phone number
  3. Extention

This same answer was given here: A comprehensive regex for phone number validation (direct link to my answer)

like image 25
Ismael Miguel Avatar answered Oct 09 '22 21:10

Ismael Miguel