Regex для номера телефона js

let isPhoneNumber = input => {

  try {
    let ISD_CODES = [93, 355, 213, 1684, 376, 244, 1264, 672, 1268, 54, 374, 297, 61, 43, 994, 1242, 973, 880, 1246, 375, 32, 501, 229, 1441, 975, 591, 387, 267, 55, 246, 1284, 673, 359, 226, 257, 855, 237, 1, 238, 1345, 236, 235, 56, 86, 61, 61, 57, 269, 682, 506, 385, 53, 599, 357, 420, 243, 45, 253, 1767, 1809, 1829, 1849, 670, 593, 20, 503, 240, 291, 372, 251, 500, 298, 679, 358, 33, 689, 241, 220, 995, 49, 233, 350, 30, 299, 1473, 1671, 502, 441481, 224, 245, 592, 509, 504, 852, 36, 354, 91, 62, 98, 964, 353, 441624, 972, 39, 225, 1876, 81, 441534, 962, 7, 254, 686, 383, 965, 996, 856, 371, 961, 266, 231, 218, 423, 370, 352, 853, 389, 261, 265, 60, 960, 223, 356, 692, 222, 230, 262, 52, 691, 373, 377, 976, 382, 1664, 212, 258, 95, 264, 674, 977, 31, 599, 687, 64, 505, 227, 234, 683, 850, 1670, 47, 968, 92, 680, 970, 507, 675, 595, 51, 63, 64, 48, 351, 1787, 1939, 974, 242, 262, 40, 7, 250, 590, 290, 1869, 1758, 590, 508, 1784, 685, 378, 239, 966, 221, 381, 248, 232, 65, 1721, 421, 386, 677, 252, 27, 82, 211, 34, 94, 249, 597, 47, 268, 46, 41, 963, 886, 992, 255, 66, 228, 690, 676, 1868, 216, 90, 993, 1649, 688, 1340, 256, 380, 971, 44, 1, 598, 998, 678, 379, 58, 84, 681, 212, 967, 260, 263],
      //extract numbers from string
      thenum = input.match(/[0-9]+/g).join(""),
      totalnums = thenum.length,
      last10Digits = parseInt(thenum) % 10000000000,
      ISDcode = thenum.substring(0, totalnums - 10);

    //phone numbers are generally of 8 to 16 digits
    if (totalnums >= 8 && totalnums <= 16) {
      if (ISDcode) {
        if (ISD_CODES.includes(parseInt(ISDcode))) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    }
  } catch (e) {}

  return false;
}

console.log(isPhoneNumber('91-9883208806'));
let isPhoneNumber = input => {

  try {
    let ISD_CODES = [93, 355, 213, 1684, 376, 244, 1264, 672, 1268, 54, 374, 297, 61, 43, 994, 1242, 973, 880, 1246, 375, 32, 501, 229, 1441, 975, 591, 387, 267, 55, 246, 1284, 673, 359, 226, 257, 855, 237, 1, 238, 1345, 236, 235, 56, 86, 61, 61, 57, 269, 682, 506, 385, 53, 599, 357, 420, 243, 45, 253, 1767, 1809, 1829, 1849, 670, 593, 20, 503, 240, 291, 372, 251, 500, 298, 679, 358, 33, 689, 241, 220, 995, 49, 233, 350, 30, 299, 1473, 1671, 502, 441481, 224, 245, 592, 509, 504, 852, 36, 354, 91, 62, 98, 964, 353, 441624, 972, 39, 225, 1876, 81, 441534, 962, 7, 254, 686, 383, 965, 996, 856, 371, 961, 266, 231, 218, 423, 370, 352, 853, 389, 261, 265, 60, 960, 223, 356, 692, 222, 230, 262, 52, 691, 373, 377, 976, 382, 1664, 212, 258, 95, 264, 674, 977, 31, 599, 687, 64, 505, 227, 234, 683, 850, 1670, 47, 968, 92, 680, 970, 507, 675, 595, 51, 63, 64, 48, 351, 1787, 1939, 974, 242, 262, 40, 7, 250, 590, 290, 1869, 1758, 590, 508, 1784, 685, 378, 239, 966, 221, 381, 248, 232, 65, 1721, 421, 386, 677, 252, 27, 82, 211, 34, 94, 249, 597, 47, 268, 46, 41, 963, 886, 992, 255, 66, 228, 690, 676, 1868, 216, 90, 993, 1649, 688, 1340, 256, 380, 971, 44, 1, 598, 998, 678, 379, 58, 84, 681, 212, 967, 260, 263],
      //extract numbers from string
      thenum = input.match(/[0-9]+/g).join(""),
      totalnums = thenum.length,
      last10Digits = parseInt(thenum) % 10000000000,
      ISDcode = thenum.substring(0, totalnums - 10);

    //phone numbers are generally of 8 to 16 digits
    if (totalnums >= 8 && totalnums <= 16) {
      if (ISDcode) {
        if (ISD_CODES.includes(parseInt(ISDcode))) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    }
  } catch (e) {}

  return false;
}

console.log(isPhoneNumber('91-9883208806'));
let isPhoneNumber = input => {

  try {
    let ISD_CODES = [93, 355, 213, 1684, 376, 244, 1264, 672, 1268, 54, 374, 297, 61, 43, 994, 1242, 973, 880, 1246, 375, 32, 501, 229, 1441, 975, 591, 387, 267, 55, 246, 1284, 673, 359, 226, 257, 855, 237, 1, 238, 1345, 236, 235, 56, 86, 61, 61, 57, 269, 682, 506, 385, 53, 599, 357, 420, 243, 45, 253, 1767, 1809, 1829, 1849, 670, 593, 20, 503, 240, 291, 372, 251, 500, 298, 679, 358, 33, 689, 241, 220, 995, 49, 233, 350, 30, 299, 1473, 1671, 502, 441481, 224, 245, 592, 509, 504, 852, 36, 354, 91, 62, 98, 964, 353, 441624, 972, 39, 225, 1876, 81, 441534, 962, 7, 254, 686, 383, 965, 996, 856, 371, 961, 266, 231, 218, 423, 370, 352, 853, 389, 261, 265, 60, 960, 223, 356, 692, 222, 230, 262, 52, 691, 373, 377, 976, 382, 1664, 212, 258, 95, 264, 674, 977, 31, 599, 687, 64, 505, 227, 234, 683, 850, 1670, 47, 968, 92, 680, 970, 507, 675, 595, 51, 63, 64, 48, 351, 1787, 1939, 974, 242, 262, 40, 7, 250, 590, 290, 1869, 1758, 590, 508, 1784, 685, 378, 239, 966, 221, 381, 248, 232, 65, 1721, 421, 386, 677, 252, 27, 82, 211, 34, 94, 249, 597, 47, 268, 46, 41, 963, 886, 992, 255, 66, 228, 690, 676, 1868, 216, 90, 993, 1649, 688, 1340, 256, 380, 971, 44, 1, 598, 998, 678, 379, 58, 84, 681, 212, 967, 260, 263],
      //extract numbers from string
      thenum = input.match(/[0-9]+/g).join(""),
      totalnums = thenum.length,
      last10Digits = parseInt(thenum) % 10000000000,
      ISDcode = thenum.substring(0, totalnums - 10);

    //phone numbers are generally of 8 to 16 digits
    if (totalnums >= 8 && totalnums <= 16) {
      if (ISDcode) {
        if (ISD_CODES.includes(parseInt(ISDcode))) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    }
  } catch (e) {}

  return false;
}

console.log(isPhoneNumber('91-9883208806'));

Cover image for How to Match a Phone Number with Regex and JavaScript

Amit Mehta

I’ll be honest, the first time I saw a regular expression, it was a scary experience. It looks like a weird alien language! I thought to myself: «I’ve spent months learning programming and now i gotta learn this seemly super complex language!?»

However, once I sat down to actually learn regex, I discovered it’s not super hard, once you learn the syntax.

Why should I even bother Learning Regex?

As you start coding more, and more, it really comes in handy in all types of situations, and not just to valid phone numbers, and email addresses. It’s very helpful when extract data from logs, messy JSON data from API calls, and many other situations.

I’m going to teach you how to valid a phone number with 1 line of code, with 1 regular expression. *Validating a phone number WITHOUT regex becomes an obnoxious leetcode question. * 😧

Why is validating a phone number so complex?

Let’s say you have a form on your website to collect a phone number to spa-, I mean, SMS your subscribers, there are a bunch of different ways they could submit their phone numbers.

All of these are VALID US based numbers:

  • 202-515-5555
  • 202 515 5555
  • (202)515 5555
  • 1 202 515 5555
  • 2025155555
  • 1-202-515-5555
  • 1202-515-5555
  • etc

There are more valid combinations I didn’t list, but you get the idea! Validating every combo because a nasty coding problem. *But NOT if you’re using regex to validate it! * 😉

Let’s start with the Simplest Case

Let’s first validate 202-515-5555. The basic idea of regex is to build a pattern to match a string. What is the pattern in 202-515-5555 ?

We start with 3 digits followed by a - followed by 3 more digits, followed by another -, then we end with 4 digits.

Here’s what the regex pattern to match 202-515-5555 looks like:

^d{3}-d{3}-d{4}$

Enter fullscreen mode

Exit fullscreen mode

Let’s watch through this…

The ^ just indicates the beginning of the string. In the above regex, we’re stating that the phone number must start with d{3} since we have ^ in front of d{3}.

Now d => stands for single digit, and {3} simple means d repeats exactly 3 times.
So ^d{3} means our phone number STARTS with 3 digits.

Now let’s just jump to the end: $ indicates the end of the string match. d{4}$ means our phone number must END with 4 digits. Does this make sense?

- just means the phone number must have a dash at that spot.

So let’s read the entire regex from left to right now:

  1. ^d{3} ⇾ start with 3 digits
  2. - ⇾ followed by a dash
  3. d{3} ⇾ followed with 3 digits
  4. - ⇾ followed by a dash
  5. d{4}$ ⇾ ends with 4 digits

Please read the above section a few times, if necessary, to make sure you fully understand before we move on.

How do I match the phone number if dashes are options?

Great question! How do we match BOTH: 202-515-5555 and 2025155555

To make a character match optional, just add a ? after it.

Here’s what our new improved match looks like:

^d{3}-?d{3}-?d{4}$

Enter fullscreen mode

Exit fullscreen mode

-? simply means the - is optional: it may, or may not, be there!

Let’s read the entire regex again:

  1. ^d{3} ⇾ start with 3 digits
  2. -?optionally followed by a dash
  3. d{3} ⇾ followed with 3 digits
  4. -?optionally followed by a dash
  5. d{4}$ ⇾ ends with 4 digits

How about matching the phone number if there are spaces, instead of dashes?

Now let’s work on matching: 202-515-5555, 2025155555, AND 202 515 5555

Instead of optionally just having a - we can optionally have either - OR . How do we represent this? Easy, put both - and inside of [...] like this: [ -].

Our new regex looks like this:

^d{3}[ -]?d{3}[ -]?d{4}$

Enter fullscreen mode

Exit fullscreen mode

Now it’s definitely starting to look alien! 😅

Let’s break it down:

  1. ^d{3} ⇾ start with 3 digits
  2. [ -]?optionally followed by a space OR dash
  3. d{3} ⇾ followed with 3 digits
  4. [ -]?optionally followed by a space OR dash
  5. d{4}$ ⇾ ends with 4 digits

How to Match 1 or 1 or 1- at the beginning of our phone number

Based on what we’ve learned, can you figure this out?

It’s a bit tricky once you realize that the 1... in the beginning is optional.

Let’s take it step by step…

If you want the phone number to start with 1 we add ^1 to the beginning of the string match, correct? Now we want to optionally add a dash or space after the 1. Luckily, we already know how to do that: [ -]?.

Combining the 2 we get: ^1[ -]?

Adding this to our previous regex we get:

^1[ -]?d{3}[ -]?d{3}[ -]?d{4}$

Enter fullscreen mode

Exit fullscreen mode

Can you sense there’s something wrong here? The above regex string match MUST start with 1, it’s not optional. We need to make 1[ -]? optional.

How do we do that? Since we’re talking about multiple elements here: 1 and [ -]? we need to place the whole thing in (...) creating a group. Then add a ? after it to make the entire group optional!

I know it’s a lot to take in! Here’s what it looks like:

^(1[ -]?)?d{3}[ -]?d{3}[ -]?d{4}$

Enter fullscreen mode

Exit fullscreen mode

Let’s break it down again, with an extra step now:

  1. ^(1[ -]?)?optionally start with 1, which is optionally followed by a space OR dash
  2. d{3} ⇾ start with 3 digits
  3. [ -]?optionally followed by a space OR dash
  4. d{3} ⇾ followed with 3 digits
  5. [ -]?optionally followed by a space OR dash
  6. d{4}$ ⇾ ends with 4 digits

🤯

If you’re still reading, congrats, you now know how to think ‘regex’!

Picard Regex

There’s still 1 outstanding issue: how to match a phone number like: (202)515 5555. I’m going to leave that one for the reader (hint: use the pipe operator: (...|...)).

Putting it all Together to Test an Actual Phone Number String

Now let’s take our regex and turn it into a regular expression in javaScript. To do that you just add /.../ around it. Then use a method called test:

const regex = /^(1[ -]?)?d{3}[ -]?d{3}[ -]?d{4}$/;
const phoneNumber = '1202-515-5555';

// test returns 'true' if there's a match and 'false' if there is not
const match = regex.test(phoneNumber);

Enter fullscreen mode

Exit fullscreen mode

If you want to learn regex properly, here’s a EXCELLENT free tutorial: RegexOne. This is literally how I learned Regex. It’s worth going through ALL the exercises.

If you enjoyed this article please check out my blog
Indepth JavaScript for more illuminating
content. 🤓

Проверка адреса email и номера телефона на javascript

Предоставляя пользователю возможность заполнения полей на сайте, следует проверять введенные данные на валидность. Это позволит предупредить пользователя о случайных ошибках, а так же даст дополнительную защиту от спама. Ярким примером является форма обратной связи, обязательными полями которой часто бывают email и телефон. Займемся их проверкой на правильность заполнения с помощью javascript.

Информация лучше воспринимается на примерах, поэтому посмотрим готовую форму в действии:

Пожалуйста, заполните все поля формы!

Для начала разберем применяемые регулярные выражения, а полный код формы и javascript функций я приведу в конце статьи.

Валидность адреса электронной почты

Рассмотрим адрес электронной почты (test@mail.ru). Вот его обязательные части:

  • Название (test) — один или много символов;
  • Знак собаки (@);
  • Доменное имя почтового сервера (mail) — один или много символов;
  • Точка (.);
  • Доменное имя первого уровня (ru) от двух до пяти букв.

Составим регулярное выражение для наших требований:

/^[w-.]+@[w-]+.[a-z]{2,4}$/i

Разберём правило по частям:

  1. Регулярное выражение должно открываться и закрываться символами «/». После закрывающегося символа можно указать директиву. В нашем случае такой директивной является «i», которая отключает проверку вводимых букв на регистр. То есть, становится не важно, ввели «test@mail.ru» или «Test@Mail.RU».
  2. Знаки «^» и «$» обозначают начало и конец проверяемой строки. Если их убрать, то правило вернет положительный результат даже если в начале или конце электронного адреса поставить запрещенные знаки. То есть, при вводе «%:&test@mail.ru#6&» функция проверки вернет положительный результат, так как в строке имеется последовательность символов, удовлетворяющая нашему правилу. Для исключения такой возможности указываем, что правило должно применяться ко всей строке, а не к её части.
  3. Блок «[w-.]+» отвечает за проверку названия ящика. В квадратных скобках указываем разрешенные символы: «w» — все латинские буквы, цифры и знак подчеркивания. Так же рекомендую добавлять знак тире и точку «-.». «+» после квадратных скобок указывает на возможность повторения символов — один или много раз.
  4. Далее идет знак собаки и доменное имя почтового сервера — «@[w-]+». Здесь практически тоже самое что и в предыдущем блоке. Исключаем только из набора символов точку.
  5. Осталось прописать правило для проверки наличия точки и корректности доменного имени верхнего уровня (ru,com,info). «.[a-z]{2,4}». Для обозначения знака точки мы указываем её с обратным слешем «.» Без него она будет восприниматься зарезервированным символом регулярки, который обозначает возможность наличия на её месте любого символа.

    За точкой должно следовать доменное имя верхнего уровня. Это минимум 2 латинские буквы — «[a-z]{2,4}».

Разобранный пример немного упрощен для лучшего восприятия. У него есть недостаток — первым знаком в email не может быть тире или точка, но приведенное регулярное выражение этого не учитывает. Чтобы это исправить следует его немного поправить:

/^[w]{1}[w-.]*@[w-]+.[a-z]{2,4}$/i

Проверка валидности номера телефона в javascript

С номером телефона ситуация сложнее, так как номер можно ввести десятками способов:

8 999 1234567
8 (999) 1234567
8 999 123-45-67
+7 (999) 123 45 67

Есть несколько выходов из ситуации:

  • продумать все возможные шаблоны и составлять для них правила;
  • заставить посетителя вводить телефон по определенному шаблону;
  • ограничиться проверкой на случайные ошибки.

Для форм обратной связи последний вариант кажется наилучшим. Во-первых, если человек не хочет указывать свой номер телефона, то никакие проверки на корректность не помогут. Он просто введет несуществующий или чужой номер. Во-вторых, посетители сайта не любят когда их загоняют в определенные рамки. Поэтому рекомендую использовать регулярное выражение следующего типа:

/^[d+][d() -]{4,14}d$/

В правиле указываем что первый символ должен быть обязательно цифрой или плюсом «[d+]», а последний только цифрой — «d». В середине разрешаем использовать скобоки, пробел и знак дефиса — «[d() -]{4,14}», от 4 до 14 символов. Так как скобки и пробел являются зарезервированными элементами регулярных выражений, перед ними ставим обратный слеш.

Для любителей жестких шаблонов приведу пример проверки номера вида 8 (999) 123-45-64

/^[d]{1} ([d]{2,3}) [d]{2,3}-[d]{2,3}-[d]{2,3}$/

Исходный код примера: html и javascript

Это полный код тестовой странички, на которой я использовал форму и js скрипты для отладки правил из этой статьи. Можете скопировать его и протестировать у себя на компьютере.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript">
 
function ValidMail() {
    var re = /^[w-.]+@[w-]+.[a-z]{2,4}$/i;
    var myMail = document.getElementById('email').value;
    var valid = re.test(myMail);
    if (valid) output = 'Адрес эл. почты введен правильно!';
    else output = 'Адрес электронной почты введен неправильно!';
    document.getElementById('message').innerHTML = output;
    return valid;
}
 
function ValidPhone() {
    var re = /^[d+][d() -]{4,14}d$/;
    var myPhone = document.getElementById('phone').value;
    var valid = re.test(myPhone);
    if (valid) output = 'Номер телефона введен правильно!';
    else output = 'Номер телефона введен неправильно!';
    document.getElementById('message').innerHTML = document.getElementById('message').innerHTML+'<br />'+output;
    return valid;
}  
 
</script>

</head>

<body>
<p id="message" >Пожалуйста, заполните все поля формы!</p> 
E-mail: <input id="email" name="email" type="text" size="20" /><br /> 
Телефон: <input id="phone" name="phone" type="text" size="20" /><br /> 
<input name="button" type="submit" value="Проверить" onClick="ValidMail(); ValidPhone();" />
</body>

</html>

Это демонстрационная версия. В случае с формой обратной связи нам следует проводить проверку полей не при нажатии на кнопку, а при попытке отправить её:

<form action="/feedback/" method="post" onsubmit="return (ValidMail()&&ValidPhone())">

В этом случае форма отправится только если обе функции вернут значение «true».

  1. HowTo
  2. JavaScript Howtos
  3. Phone Number RegEx in JavaScript

Shraddha Paghdar
Nov 15, 2021

Phone Number RegEx in JavaScript

Each country has its own number format, and before we store this data in the database, we need to make sure that the user is entering the correct number format. In this post, we’re going to learn how to write regular expressions for phone numbers in JavaScript.

RegEx in JavaScript

Regular expressions are like a search tool that can find specific patterns in strings. A good resource to learn RegEx is https://regexr.com. JavaScript also supports regular expressions as an object. These patterns are used with the matchAll(), match(), replaceAll(), replace(), search(), and split(). There are two ways to construct the regular expression, use a literal regular expression and call the constructor function of the RegExp object.

Let’s understand some of the common patterns before we move on to the phone number RegEx.

  • d: This regular expression matches any number/digit. It is similar to [0-9].
  • w: This regular expression matches any given word character code in the range of AZ, az, 09 and _.
  • s: This regular expression matches every whitespace character, such as spaces, tabs, line breaks.
  • b: This regular expression matches any word boundary position between a word character and a non-word character or a position (beginning/end of the character string).
  • [A-Z]: This regular expression matches any given character code in the range from AZ.
  • [0-9]: This regular expression matches any given character code in the range from 09.
  • (?:ABC): This regular expression groups multiple tokens together without creating a capturing group.

Each RegEx contains certain tags listed below:

  • i: This flag means that it is case insensitive, which means that the entire expression is not case sensitive.
  • g: This flag means a global search that maintains the index of the last match so that subsequent searches can start at the end of the previous match. Without the global flag, subsequent searches will return the same match.
  • m: This flag means multi-line. When the multi-line flag is on, the start and end anchors (^ and $) match the beginning and end of a line, not the beginning and end of the entire chain.
  • u: This flag means Unicode. Users can use extended Unicode escapes of the form x {FFFFF} by activating this flag.
  • y: This flag means sticky. The expression only matches its lastIndex position and ignores the global flag (g) if it is set. Since every search in RegEx is discrete, this indicator has no further effect on the displayed results.
  • s: This flag means dotAll. A period (.) matches each character, including the new line.

Syntax of RegEx in JavaScript

const regEx = /pattern/;  
const regEx = new RegExp('pattern');

Example Code:

<form name="form1">
  <input type='text' id="phoneNumber" name='text1'/>
  <button type="submit" name="submit" onclick="phonenumber()">Submit</button>
</form>
function phonenumber()
{
    const indiaRegex = /^+91d{10}$/;
    const inputText = document.getElementById("phoneNumber").value;
    if(inputText.match(indiaRegex)) {
	    console.log("Valid phone number");      
    } else {
	   console.log("Not a valid Phone Number");
    }
}

Output:

phone number regex in JS

Shraddha Paghdar avatar
Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

Related Article — JavaScript Regex

  • Regex Variable in JavaScript
  • Match Multiple Occurrences With Regex in JavaScript
  • Validate Email With Regex in JavaScript
  • Regular Expression for JavaScript to Allow Only Alphanumeric Characters
  • JavaScript Remove Special Characters
  • JavaScript Replace With Regex

Ezoic

Понравилась статья? Поделить с друзьями:
  • Raiffeisen online номер телефона
  • Raiffeisen bank номер телефона
  • R4in номер телефона
  • R line махачкала номер телефона техподдержки
  • R line каспийск номер телефона