US Phone Number Validation in JavaScript

US Phone Number Validation in JavaScript
Code Snippet:Telephone Number Validator
Author: Aleksandar Sandro Cvetković
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 731
License: MIT
Edit Code online: View on CodePen
Read More

Are you looking to verify US telephone numbers easily? This JavaScript code provides a user-friendly way for US phone number validation. With a simple interface, just input your number and hit “Validate” to check its validity. The code also includes a theme switch for customizing your experience.

It enhances user experience by providing real-time validation feedback, reducing errors during data input. Additionally, the theme switch functionality allows your users to customize the site’s appearance.

How to Validate US Phone Number in JavaScript

1. Within your HTML, create a container for the validation form. Include an input field for the telephone number, a “Validate” button, and an empty div for displaying validation results.

<div id="container">
      <h1>Telephone Number Validator</h1>
      <p class="sub-text">
        This Telephone Number Validator is only for US numbers.
      </p>
      <input id="check" type="text" placeholder="Type telephone number..." />
      <button onclick="telephoneCheck(check.value)">
        Validate
      </button>

      <div id="print"></div>

      <div class="panel">
        <div class="theme-switch-wrapper">
          <label class="theme-switch" for="checkbox">
            <input type="checkbox" id="checkbox" />
            <div class="slider round"></div>
          </label>
          <em>Change Theme</em>
        </div>
      </div>
    </div>

2. If needed, modify the CSS code to match your website’s styling. You can change colors, fonts, and layout as desired to seamlessly integrate the validation form into your website’s design.

:root {
  --primary-color: #0a79df;
  --secondary-color: #536390;
  --font-color: #424242;
  --bg-color: #fff;
  --heading-color: #292922;
  --panel-color: #fff;
  --border-color: #111;
}

[data-theme=dark] {
  --primary-color: #9a97f3;
  --secondary-color: #818cab;
  --font-color: #e1e1ff;
  --bg-color: #161625;
  --heading-color: #818cab;
  --panel-color: #111;
  --border-color: #fff;
}


body {
  font-family: "Lato", sans-serif;
  background-color: var(--bg-color);
  color: var(--font-color);
  max-width: 90%;
  margin: 0 auto;
  font-size: calc(1rem + 0.25vh);
}

#container {
  max-width: 70%;
  margin: 30px auto;
  padding: 30px 30px;
}

h1 {
  color: var(--heading-color);
  font-family: "Sansita", sans-serif;
  font-size: 2rem;
  margin-bottom: 1vh;
}

.panel {
  display: flex;
  justify-content: center;
  padding: 10px 0px;
  background-color: var(--panel-color);
  border: 1px solid var(--border-color);
}

.sub-text {
  font-size: 1rem;
  font-style: italic;
  margin-bottom: 4vh;
  color: var(--secondary-color);
}

p {
  font-size: 1.1rem;
  line-height: 1.6rem;
}

input,
button {
  border: 1px solid #0a79df;
  border-radius: 3px;
  display: block;
  margin: 15px 0;
  font-size: 16px;
  padding: 8px 10px;
}

button {
  background-color: #0a79df;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
  cursor: pointer;
}

#print {
  margin: 30px 0px 30px;
  padding: 10px 0px;
}

/* Slider Switch */
.theme-switch-wrapper {
  display: flex;
  align-items: center;
}
.theme-switch-wrapper em {
  margin-left: 15px;
  font-size: 1rem;
}

.theme-switch {
  display: inline-block;
  height: 34px;
  position: relative;
  width: 60px;
}

.theme-switch input {
  display: none;
}

.slider {
  background-color: #ccc;
  bottom: 0;
  cursor: pointer;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: 0.4s;
}

.slider:before {
  background-color: #fff;
  bottom: 4px;
  content: "";
  height: 26px;
  left: 4px;
  position: absolute;
  transition: 0.4s;
  width: 26px;
}

input:checked + .slider {
  background-color: #0a79df;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

3. Finally, add the following JavaScript code to your project. The telephoneCheck function uses regular expressions to validate the US phone number entered in the input field. Valid numbers are displayed in green, while invalid numbers are shown in red below the input field.

// Switch Theme
const toggleSwitch = document.querySelector(
  '.theme-switch input[type="checkbox"]'
);
const currentTheme = localStorage.getItem("theme");

if (currentTheme) {
  document.documentElement.setAttribute("data-theme", currentTheme);

  if (currentTheme === "dark") {
    toggleSwitch.checked = true;
  }
}

function switchTheme(e) {
  if (e.target.checked) {
    document.documentElement.setAttribute("data-theme", "dark");
    localStorage.setItem("theme", "dark");
  } else {
    document.documentElement.setAttribute("data-theme", "light");
    localStorage.setItem("theme", "light");
  }
}

toggleSwitch.addEventListener("change", switchTheme, false);

// Check Telephone Number
function telephoneCheck(str) {
  var regex = /^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$/;
  console.log(regex.test(str));

  if (regex.test(str) === true) {
    return (document.getElementById("print").innerHTML =
      "<span style='color: green;'>Your telephone number is valid!</span>");
  }
  return (document.getElementById("print").innerHTML =
    "<span style='color: red;'>Your telephone number is not valid!</span>");
}

That’s all! hopefully, you have successfully created US Phone Number Validation Javascript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X