Form Validation using JS Regular Expressions

Web Design

In this tutorial we are goin to create a registration form in HTML and CSS and also use materialize css classes. In order to validate the form we are going to use JavaScript regular expressions to validate name input, phone number input validation, zip code input validation, password input validation, email input validation. After all of the input fields are valid we will submit the form.

Source Code:

HTML:

<h1>Form Validation using RegEx</h1>

    <div class="form=container">
      <form class="col s12">
        <div class="input-container">
          <label for="FullName">Name</label>
          <input placeholder="Enter Your Full Name" id="FullName" type="text" />
        </div>
        <div class="input-container">
          <label for="Phone">Phone</label>
          <input id="Phone" type="text" />
        </div>

        <div class="input-container">
          <label for="zipCode">Zip Code</label>
          <input id="zipCode" type="text" />
        </div>

        <div class="input-container">
          <label for="Password">Password</label>
          <input id="Password" type="password" />
        </div>

        <div class="input-container">
          <label for="Email">Email</label>
          <input id="Email" type="email" />
        </div>
        <input type="submit" value="Submit" class="btn red" />
      </form>
    </div>

CSS:

input.notValid {
  color: red !important;
  border-bottom: 1px solid red !important;
}

JS:

// Todo: get DOM elements and add EventListeners to them
// get Elements
const fullName = document.getElementById("FullName");
const phone = document.getElementById("Phone");
const zipCode = document.getElementById("zipCode");
const eMail = document.getElementById("Email");
const password = document.getElementById("Password");

// add EventListeners
fullName.addEventListener("blur", validateName);
phone.addEventListener("blur", validatePhone);
zipCode.addEventListener("blur", validateZipCode);
eMail.addEventListener("blur", validateEmail);
password.addEventListener("blur", validatePassword);

Useful resources:

Mozila develope network

MDN

Leave a Reply

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