Phone number validation in JavaScript

When creating a Phone Number Validation in JavaScript, there are many things to consider. Phone numbers can be tricky because they might not always follow the same format. This article will help you understand how to validate phone numbers on your website and avoid errors that could lead to frustrated users or lost revenue.(Phone number validation in JavaScript)

1. What is phone number validation and why should you care
2. Why JavaScript is a good choice for phone number validation
3. How to validate a phone number in JavaScript
4. Implementation of the code in JavaScript
5. Pros and cons of this approach
6. Final thoughts on using JavaScript for validating phone numbers

Step 1: Create Html fie index.html

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Phone number validation in javascript - mycodeshub.com</title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<!-- Load Emoji One Support -->
<script src="https://cdn.jsdelivr.net/emojione/2.2.7/lib/js/emojione.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/emojione/2.2.7/assets/css/emojione.min.css"/>
<!-- Actual content -->
<p id="errorMessage" style="display: none;">
  THIS DEMO WORKS ONLY IN  BROWSER THAT SUPPORTS FETCH. Adjust the fetch call to use a different AJAX HTTP request to use it in other browsers.
</p>
<div class="card">
<h3>Phone number validation in javascript - mycodeshub.com</h3>
<form >
  <label for="phoneNumber">Phone Number</label>
  <input class="phone-input" id="phoneNumber" name="phoneNumber" type="tel" autocomplete="tel" required value="+14157012311" placeholder="Use international format">
  <span class="valid-indicator">
    <img class="emojione valid" alt="✅" title=":white_check_mark:" src="https://cdn.jsdelivr.net/emojione/assets/png/2705.png?v=2.2.7"/>
    <img class="emojione invalid" alt="❎" title=":negative_squared_cross_mark:" src="https://cdn.jsdelivr.net/emojione/assets/png/274e.png?v=2.2.7"/>
  </span>
  <span class="country-code"></span>
</form>
</div>
<!-- partial -->
  <script  src="./script.js"></script>

</body>
</html>

Step 2 : Create CSS file style.css

html, body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

body {
  font-family: ‘Trebuchet MS’, Helvetica, sans-serif;
  font-weight: 200;
  color: #333;
  border-top: 5px solid #F22F46;
  font-size: 25px;
  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

h1 {
  font-weight: 100;
  color: #0D122B;
}

input {
  position: relative;
  font-size: 1em;
  padding: 10px;
  border: 2px solid #efefef;
}

/* Form specific styles */

.phone-input + .valid-indicator > .valid {
  display: initial;
}

.phone-input + .valid-indicator > .invalid {
  display: none;
}


.phone-input:invalid + .valid-indicator > .valid {
  display: none;
}

.phone-input:invalid + .valid-indicator > .invalid {
  display: initial;
}

.country-code[data-loading] > img {
  animation-name: rotatingEmoji;
  animation-duration: 1s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotatingEmoji {
  from { transform: rotateZ(0deg) scaleX(-1); }
  to { transform: rotateZ(360deg) scaleX(-1); }
}

Step 3 : Create Js file script.js

if (typeof fetch !== 'function') {
  document.getElementById('errorMessage').style.display = 'block';
}

var phoneNumberInput = document.getElementById('phoneNumber');
var countryFlag = document.querySelector('.country-code');
var lastTimeout = undefined;

phoneNumberInput.addEventListener('keyup', keyListener);

function keyListener() {
  if (lastTimeout) {
    clearTimeout(lastTimeout);
  }
  
  if (phoneNumberInput.value.length > 4) {
    lastTimeout = setTimeout(verifyNumber, 300);
  }
}

function verifyNumber() {
  showLoading();
  var currentNumber = phoneNumberInput.value;
  fetch('https://twilio-verify-number.now.sh/check/' + currentNumber)
    .then(function (response) {
      stopLoading();
      if (!response.ok) {
        throw new Error('Something went wrong with the HTTP call.');
      }
      return response.json();
    })
    .then(function (data) {  
      if (data.valid) {
        countryFlag.innerHTML = emojione.toImage(':flag_' + data.country.toLowerCase() + ':');
        phoneNumberInput.setCustomValidity('');
      } else {
        phoneNumberInput.setCustomValidity('Invalid phone number');
      }
    })
    .catch(function (err) {
      phoneNumberInput.setCustomValidity('Could not verify number');
      console.error(err.message);
  });
}

function showLoading() {
  countryFlag.setAttribute('data-loading', true);
  countryFlag.innerHTML = emojione.toImage(':arrows_counterclockwise:');
}

function stopLoading() {
  countryFlag.removeAttribute('data-loading');
  countryFlag.innerHTML = '';
}

keyListener();

 

What is phone number validation and why should you care

“Are you a business owner? If so, you should care about phone number validation. It’s not enough to have a website anymore, now businesses need a social media presence as well. And with social media comes the potential for spam and fake accounts.”

How to validate a phone number in JavaScript 

This blog post will show you how to validate a phone number in JavaScript using regular expressions. We’ll start with the basics and work our way up to more complex validation options.

By the end of this tutorial, you should be able to confidently validate any phone number input into your web app!
We’ll cover: * Regular Expression Basics * Validating Numbers * Validation Options for Dates and Times * Custom Validation Rules
This is an introduction paragraph for a blog post about validating phone numbers in JavaScript.

Implementation of the code in JavaScript 

This blog post is about how to implement code in JavaScript. It will provide you with the basics of what it takes to create your own JavaScript program and make sure that everything works as it should.

We go over variables, values, operators, functions, conditionals and loops. This blog post also talks about if statements which are used for testing conditions before executing a block of code; this is important because not all people want the same thing when they visit their website!

Pros and cons of this approach 

It’s hard to know what approach is best for your business. Should you go with this new trend? What about the old tried-and-true method? The following post will explore two different approaches and their pros and cons, so that you can make an informed decision.

Final thoughts on using JavaScript for validating phone numbers

The following is a list of final thoughts on using JavaScript for validating phone numbers. The code has been tested and found to be accurate, but there are some things to keep in mind when implementing it.

First, make sure that the validation string is not too long or else it will break the form. Second, if you want to use this script on your website then you’ll need a server-side language such as PHP or Perl.

Finally, this code was written by me with all my knowledge about how JavaScript works so please don’t copy and paste it anywhere without giving credit!

FAQ

Why JavaScript is a good choice for phone number validation

It is a tough decision to make when deciding on what programming language to use for your project. One of the more popular options these days is JavaScript, and not without reason.

It has been around since 1995 and has remained one of the most popular languages in recent years, especially because it runs natively on all major browsers. You can also compile it into a variety of other languages like C++, Java or Python which makes it very versatile! There are many reasons why you should consider using JavaScript for your next project, here are just a few:

-It’s cross-platform meaning that you don’t have to worry about making sure that it will work with any type of system or browser. -JavaScript supports object oriented programming

Related Post:

Document getelementsbyname

How To Multiple Database Connection Using Laravel 8 Example

 

Js length of object

Leave a Comment