Phone number check in javascript

Phone number regex

The regular expressions below can be used to validate if a string is a valid phone number format and to extract a phone number from a string. Please note that this validation can not tell if a phone number actually exists.

The basic international phone number validation

A simple regex to validate string against a valid international phone number format without delimiters and with an optional plus sign:

Enter a text in the input above to see the result

Example code in Javascript

 

The more complex phone number validation

This regular expression will match phone numbers entered with delimiters (spaces, dots, brackets, etc.)

Enter a text in the input above to see the result

Example code in Javascript

 

Enter a text in the input above to see the result

Extra information about validating phone number

While validation of phone numbers using regex can give a possibility to check the format of the phone number, it does not guarantee that the number exists.

There might be also an option to leave a phone number field without any validation since some users might have:

  • More complex phone numbers with extensions
  • The different phone numbers for calling them on a different time of day

Create an internal tool with UI Bakery

Discover UI Bakery – an intuitive visual internal tools builder.

Источник

JavaScript: HTML Form - Phone Number validation

The validating phone number is an important point while validating an HTML form. In this page we have discussed how to validate a phone number (in different format) using JavaScript :

At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation and there will be no + sign in front the number. Simply the validation will remove all non-digits and permit only phone numbers with 10 digits. Here is the function.

function phonenumber(inputtxt) < var phoneno = /^\d$/; if((inputtxt.value.match(phoneno)) < return true; >else < alert("message"); return false; >> 

Flowchart : JavaScript phone validation-1

To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
use the following code.

function phonenumber(inputtxt) < var phoneno = /^\(?(7)\)?[-. ]?(2)[-. ]?(4)$/; if((inputtxt.value.match(phoneno)) < return true; >else < alert("message"); return false; >> 

Flowchart : JavaScript - phone validation-2

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code.

 function phonenumber(inputtxt) < var phoneno = /^\+?(2)\)?[-. ]?(1)[-. ]?(3)$/; if((inputtxt.value.match(phoneno)) < return true; >else < alert("message"); return false; >> 

Flowchart : JavaScript - phone validation-3

Following code blocks contain actual codes for the said validations. We have kept the CSS code part common for all the validations.

 li .mail < margin: auto; padding-top: 10px; padding-bottom: 10px; width: 400px; background : #D8F1F8; border: 1px soild silver; >.mail h2 < margin-left: 38px; >input < font-size: 20pt; >input:focus, textarea:focus < background-color: lightyellow; >input submit < font-size: 12pt; >.rq

Validate a 10 digit phone number

At first we validate a phone number of 10 digit. For example 1234567890, 0999990011, 8888855555 etc.

JavaScript Code

function phonenumber(inputtxt) < var phoneno = /^\d$/; if(inputtxt.value.match(phoneno)) < return true; >else < alert("Not a valid Phone Number"); return false; >> 

Flowchart : JavaScript - phone validation 10 digit

Validate North American phone numbers

Now, let's see how to validate a phone number, either in 222-055-9034, 321.789.4512 or 123 256 4587 formats.

JavaScript Code

function phonenumber(inputtxt) < var phoneno = /^\(?(8)\)?[-. ]?(1)[-. ]?(2)$/; if(inputtxt.value.match(phoneno)) < return true; >else < alert("Not a valid Phone Number"); return false; >> 

Flowchart : JavaScript - phone validation North America

Validate an international phone number with country code

Now, let's see how to validate a phone number with country code, either in +24-0455-9034, +21.3789.4512 or +23 1256 4587 format.

JavaScript Code

function phonenumber(inputtxt) < var phoneno = /^\(?(2)\)?[-. ]?(9)[-. ]?(1)$/; if(inputtxt.value.match(phoneno)) < return true; >else < alert("Not a valid Phone Number"); return false; >> 

Flowchart : JavaScript - phone validation international

Other JavaScript Validation :

  • Checking for non-empty
  • Checking for all letters
  • Checking for all numbers
  • Checking for floating numbers
  • Checking for letters and numbers
  • Checking string length
  • Email Validation
  • Date Validation
  • A sample Registration Form
  • Phone No. Validation
  • Credit Card No. Validation
  • Password Validation
  • IP address Validation

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

Sort array of objects by string property value

It's easy enough to write your own comparison function:

function compare( a, b ) < if ( a.last_nom < b.last_nom )< return -1; >if ( a.last_nom > b.last_nom ) < return 1; >return 0; > objs.sort( compare );
objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0));
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Validate Phone Numbers with Javascript & HTML

Phone number validation is very important for your business. It allows you to verify information from clients and ensure that you are dealing with a real customer. Also, it helps you to expand your outreach effectively. In this post, you will find the details of phone number validation with JavaScript and HTML.

Don't reinvent the wheel.
Abstract's APIs are production-ready now.

Abstract's suite of API's are built to save you time. You don't need to be an expert in email validation, IP geolocation, etc. Just focus on writing code that's actually valuable for your app or business, and we'll handle the rest.

How to validate a phone number using a JavaScript Regex

JavaScript Regex stands for “JavaScript Regular expressions.” It refers to a sequence of characters that forms a search pattern. By using it, you can validate phone number Javascript.

Here is the JavaScript Regex that you will use for phone number validation:

  • /^\(?: The number may start with an open parenthesis.
  • (\d): Then three numeric digits must be entered for valid formats. If there is no parenthesis, the number must start with these digits.
  • \)?: It allows you to include a close parenthesis.
  • [- ]?: The string may optionally contain a hyphen. It can be placed either after the parenthesis or following the first three digits. For example, (123)- or 123-.
  • (\d): Then the number must contain another three digits. For example, it can look like this: (123)-456, 123-456, or 123456.
  • [- ]?: It allows you to include an optional hyphen in the end, like this: (123)-456-, -123- or 123456-.
  • (\d)$/: Finally, the sequence must end with four digits. For example, (123)-456-7890, 123-456-7890, or 123456-7890.

How do you use Regex in JavaScript? Here is a function that you will use to validate phone number:

 function validatePhoneNumber(input_str) < var re = /^\(?(\d)\)?[- ]?(\d)[- ]?(\d)$/; return re.test(input_str); > 

By using this function, you can validate phone numbers entered in this format:

Validate a Phone Number Using a JavaScript Regex and HTML

To validate a phone number using the JavaScript regex and HTML, you just need to follow these steps:

1. Create an HTML file. Then add these lines:

 div form div label for="myform_phone" Phone: /label input type="text" name="phone" div Please enter a valid phone number /div /div div button type="submit" Submit /button> /div /form /div 

2. Create a CSS file. Then insert this code:

3. Create a JavaScript file. Add these lines:

 function validatePhoneNumber(input_str) < var re = /^\(?(\d)\)?[- ]?(\d)[- ]?(\d)$/; return re.test(input_str); > function validateForm(event) < var phone = document.getElementById('myform_phone').value; if (!validatePhoneNumber(phone)) < document.getElementById('phone_error').classList.remove('hidden'); >else < document.getElementById('phone_error').classList.add('hidden'); alert("validation success") >event.preventDefault(); > document.getElementById('myform').addEventListener('submit', validateForm); 

The output will look like this:

Now, if you add a phone number with the correct format, like (123) 456-7890, you will receive an alert showing “validation success”.

Validating a phone number with HTML5 “tel” input

A much better way for phone number validation from user input is using HTML5 tel input (). It helps you to create input fields for phone numbers even in international formats. It is used as follows:

 input type="tel" name="phone" pattern="5-3-3" required 

As you can see, the type attribute has been set to “tel.” Also, it has a pattern attribute, which takes a regular expression: "8-4-2". It will be used during the phone number validation.

By using the HTML5 “tel” input, you can do phone number validation with shorter code. Also, smartphone browsers can optimize the input field. They can display a keyboard to the user, which is suitable for entering phone numbers conveniently. So, it’s a much better option.

How to Validate a Phone Number with HTML5 “tel” Input

1. Add these lines to your HTML file.

 div form action="javascript:void(0)" div label for="myform_phone">Phone: /label input type="tel" name="phone" pattern="4-8-1" required/ /div div button type="submit" Submit /button /div /form /div 

2. Then insert this code to your JavaScript file:

 var phone_input = document.getElementById("myform_phone"); phone_input.addEventListener('input', () => < phone_input.setCustomValidity(''); phone_input.checkValidity(); >); phone_input.addEventListener('invalid', () => < if(phone_input.value === '') < phone_input.setCustomValidity('Enter phone number!'); >else < phone_input.setCustomValidity('Enter phone number in this format: 123-456-7890'); >>); 

Here, you are using an event listener to display a custom error message. It will show up if the phone number input is entered in an incorrect format.

The output of the code will look like this:

Let’s try adding an invalid phone number with incorrect format, like this: 01787965673. You will see a custom error message, which says “'Enter phone number in this format: 123-456-7890.”

Regional phone number formats

Using invalid phone number format can break integrations, cause data issues between platforms, and create duplicate records. It can make your phone number data very difficult to use manually. So, it’s very important to use regional phone numbers in the correct format.

Here are some of the most common regional phone number formats:

Cell phone numbers

Phone numbers in the United States consist of 11 digits — the 1-digit country code, a 3-digit area code, and a 7-digit telephone number. Let’s take a look at this example:

North American Variations

The format of North American phone numbers is a bit different. You have to enclose the area code in parentheses. Then you have to leave a space. Next, you have to hyphenate the three-digit exchange code with the four-digit number. Here is an example:

UK Variations

The UK phone number starts with a plus (+) sign, followed by its country code. Then you have to add the area code and leave a space. If you want to dial a number in London, you will have to follow this format:

Keep in mind that the area code of London is 20. If you want to dial a number in Oxford, you will have to use the area code 01.

International Dialing Codes

To format international telephone numbers in non-NANP countries, you have to add the country and area codes. You have to add a “+” sign immediately before the country code. Also, you have to separate the groups of numbers in the international phone number with spaces. Here is an example: +1 415 555 0132

While calling international numbers, you might face several dialing errors. The most common one is associated with the trunk prefix, which is a single-digit code that often starts with 0. It is added before the national subscriber number. However, you must leave out this code while dialing abroad. Otherwise, you will face issues.

London landline dialed from the UK: 020 3465 5678

The same London landline number dialed from the US: 011 44 20 3465 5678

If you look closely, you will notice that the starting zero is left out from 20.

Another common issue is associated with area codes. Unlike the US and Canada, the cell phone numbers of most countries don’t use area codes. Instead, they utilize a unified national dialing format.

You should take a look at this website, which contains dialing codes and conventions of different countries around the world. By following this information, you can avoid the issues and properly format phone numbers.

Why you should validate phone number input

Validating phone number input is very important for security. It enables you to prevent fraudulent activities, like sign-up spam. So, you will never have to worry about fake customer registrations.

To fight against spam, you can use OTP verification technology. It will send a one-time passcode to the provided phone number to ensure the accessibility of the user. It helps you to ensure that your business is getting unique and genuine sign-ups.

Validating phone numbers with an API

You can use an API to validate phone numbers conveniently. It comes with all the necessary functions to check the validity. So, you don’t have to write any code from scratch. It can make the validation process very simple. Also, it can save you a lot of time.

You can try using Abstract’s Phone Number Validation and Verification API. It’s fast, lightweight, and very easy to use. You will only need the API key to check the validity of the client’s phone number. So, you don’t have to write extra code.

 https://phonevalidation.abstractapi.com/v1/ ? api_key = YOUR_UNIQUE_API_KEY & phone = 14154582468 

If the phone number request is successful, you will see this output:

As you can see, "valid" field is set to “true.” That means the given phone number is valid. Also, it gives a variety of useful information, including the registered location, country code, and carrier. You can utilize this data to expand your outreach effectively.

Wrapping Up

Now, you have learned the way of validating phone numbers in different ways. The most efficient method is using a verification API (like with Node.js). It can make your life a lot easier.

Validate phone numbers using Abstract's API

Источник

Читайте также:  Php форматирование даты времени
Оцените статью