HomeJavascriptForm Validation Using Javascript

Form Validation Using Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to do form validation. To build this project, we need HTML, CSS and Javascript.

This is a beginner-friendly javascript project. If you are looking for more projects to improve your javascript skills you can check out this playlist here. This playlist consists of 95+ javascript projects. The difficulty of these projects varies from easy to quite complex. Hence this playlist is suitable for everyone from javascript beginners to javascript experts.

Video Tutorials:

If you are interested to learn by watching a video tutorial rather than reading this blog post you can check out the video down below. Also subscribe to my youtube channel where I post new tips, tricks and tutorials related to web development regularly.

Project Folder Structure:

Before we start coding, let us look at the project folder structure. We create a project folder called – ‘Form Validation’. Inside this folder, we have three files. The first file is index.html which is the HTML document. Next, we have the style.css file which is the stylesheet. Finally, we have the script.js file which is the script file.

HTML:

We begin with the HTML code. The HTML code creates the elements necessary to build the layout and structure of our project. We use a variety of form inputs in this project. They include text, number, email and password.

<!DOCTYPE html>
<html>
  <head>
    <title>Form Validation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <form autocomplete="off">
        <h4>Create Your Account</h4>
        <div class="input-section">
          <label>First Name <span class="required-color">*</span></label>
          <input
            type="text"
            placeholder="Enter First Name"
            id="first-name-input"
            required
          />
          <span id="first-name-error" class="hide required-color error-message"
            >Invalid Input</span
          >
          <span id="empty-first-name" class="hide required-color error-message"
            >First Name Cannot Be Empty</span
          >
        </div>
        <div class="input-section">
          <label>Last Name <span class="required-color">*</span></label>
          <input
            type="text "
            placeholder="Enter Last Name"
            id="last-name-input"
            required
          />
          <span id="last-name-error" class="hide required-color error-message"
            >Invalid Input</span
          >
          <span id="empty-last-name" class="hide required-color error-message">
            Last Name Cannot Be Empty
          </span>
        </div>

        <div class="input-section">
          <label>Email <span class="required-color">*</span></label>
          <input type="email" placeholder="Enter Email" id="email" required />
          <span id="email-error" class="hide required-color error-message"
            >Invalid Email</span
          >
          <span id="empty-email" class="hide required-color error-message"
            >Email Cannot Be Empty</span
          >
        </div>

        <div class="input-section">
          <label>Phone <span class="required-color">*</span></label>
          <input
            type="text"
            placeholder="Enter Phone Number"
            id="phone"
            required
          />
          <span id="phone-error" class="hide required-color error-message"
            >Phone Number Should Have 10 Digits</span
          >
          <span id="empty-phone" class="hide required-color error-message">
            Phone cannot be empty
          </span>
        </div>

        <div class="input-section">
          <label>Password <span class="required-color">*</span></label>
          <input
            type="password"
            placeholder="Enter Password"
            id="password"
            required
          />
          <span id="password-error" class="hide required-color error-message">
            Passwords Should Have Letter, Special symbols, Numbers And Length >=
            8
          </span>
          <span id="empty-password" class="hide required-color error-message">
            Password Cannot Be Empty
          </span>
        </div>

        <div class="input-section">
          <label>Confirm Password <span class="required-color">*</span></label>
          <input
            type="password"
            id="verify-password"
            placeholder="Confirm Password"
            required
          />
          <span
            id="verify-password-error"
            class="hide required-color error-message"
            >Should Be Same As Previous Password</span
          >
          <span
            id="empty-verify-password"
            class="hide required-color error-message"
            >Password Cannot Be Empty</span
          >
        </div>
        <button id="submit-button">Signup</button>
      </form>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Now copy the code below and paste it into your HTML document.
Next, we style the form with CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #3164ff;
}
.container {
  width: 90vw;
  max-width: 600px;
  padding: 2em 1.5em;
  background-color: #ffffff;
  margin: 1em auto;
  border-radius: 0.5em;
}
h4 {
  font-size: 1.5em;
}
.input-section {
  margin: 0.5em 0;
}
label,
.error-message {
  display: block;
  font-size: 1em;
}
label {
  margin-bottom: 0.5em;
  font-weight: 500;
}
.error-message {
  margin-top: 0.2em;
}
input,
button {
  display: block;
  outline: none;
  width: 100%;
  padding: 0.5em;
  border-radius: 0.3em;
}
input {
  padding: 1em 0.5em;
  border: 1.5px solid #d0d0d0;
}
button {
  font-size: 1em;
  background-color: #3164ff;
  border: none;
  color: #ffffff;
  padding: 0.8em 0;
  margin-top: 2em;
}
.required-color {
  color: #ff4747;
}
.error {
  border-color: #ff4747;
}
.valid {
  border-color: #37a137;
}
.hide {
  display: none;
}
@media only screen and (max-width: 450px) {
  .container {
    font-size: 14px;
  }
}

Javascript:

Finally, we implement the functionality for form validation using Javascript. Now copy the code below and paste it into your script file. We use regular expressions to validate each form field.

//First Name
let firstNameInput = document.getElementById("first-name-input");
let firstNameError = document.getElementById("first-name-error");
let emptyFirstNameError = document.getElementById("empty-first-name");

//Last name
let lastNameInput = document.getElementById("last-name-input");
let lastNameError = document.getElementById("last-name-error");
let emptyLastNameError = document.getElementById("empty-last-name");

//Phone
let phoneInput = document.getElementById("phone");
let phoneError = document.getElementById("phone-error");
let emptyPhoneError = document.getElementById("empty-phone");

//Email
let emailInput = document.getElementById("email");
let emailError = document.getElementById("email-error");
let emptyEmailError = document.getElementById("empty-email");

//Password
let passwordInput = document.getElementById("password");
let passwordError = document.getElementById("password-error");
let emptyPasswordError = document.getElementById("empty-password");

//Verify Password
let verifyPasswordInput = document.getElementById("verify-password");
let verifyPasswordError = document.getElementById("verify-password-error");
let emptyVerifyPasswordError = document.getElementById("empty-verify-password");

//Submit
let submitButton = document.getElementById("submit-button");

//Valid
let validClasses = document.getElementsByClassName("valid");
let invalidClasses = document.getElementsByClassName("error");

//Password Verification
const passwordVerify = (password) => {
  const regex =
    /^(?=.+[a-z])(?=.+[A-Z])(?=.+[0-9])(?=.+[\$\%\^\&\!@\#\*\(\)\+\=`~\?\>\<])/;
  return regex.test(password) && password.length >= 8;
};

//Text verification (if input contains only text)
const textVerify = (text) => {
  const regex = /^[a-zA-Z]{3,}$/;
  return regex.test(text);
};

//Phone number verification
const phoneVerify = (number) => {
  const regex = /^[0-9]{10}$/;
  return regex.test(number);
};

//Email verification
const emailVerify = (input) => {
  const regex = /^[a-z0-9_]+@[a-z]{3,}\.[a-z\.]{3,}$/;
  return regex.test(input);
};

//For empty input - accepts(input,empty error for that input and other errors)
const emptyUpdate = (
  inputReference,
  emptyErrorReference,
  otherErrorReference
) => {
  if (!inputReference.value) {
    //input is null/empty
    emptyErrorReference.classList.remove("hide");
    otherErrorReference.classList.add("hide");
    inputReference.classList.add("error");
  } else {
    //input has some content
    emptyErrorReference.classList.add("hide");
  }
};

//For error styling and displaying error message
const errorUpdate = (inputReference, errorReference) => {
  errorReference.classList.remove("hide");
  inputReference.classList.remove("valid");
  inputReference.classList.add("error");
};

//For no errors
const validInput = (inputReference) => {
  inputReference.classList.remove("error");
  inputReference.classList.add("valid");
};

//First name
firstNameInput.addEventListener("input", () => {
  if (textVerify(firstNameInput.value)) {
    //If verification returns true
    firstNameError.classList.add("hide");
    validInput(firstNameInput);
  } else {
    //for false
    errorUpdate(firstNameInput, firstNameError);
    //empty checker
    emptyUpdate(firstNameInput, emptyFirstNameError, firstNameError);
  }
});

//Last name
lastNameInput.addEventListener("input", () => {
  if (textVerify(lastNameInput.value)) {
    lastNameError.classList.add("hide");
    validInput(lastNameInput);
  } else {
    errorUpdate(lastNameInput, lastNameError);
    emptyUpdate(lastNameInput, emptyLastNameError, lastNameError);
  }
});

//Phone
phoneInput.addEventListener("input", () => {
  if (phoneVerify(phoneInput.value)) {
    phoneError.classList.add("hide");
    validInput(phoneInput);
  } else {
    errorUpdate(phoneInput, phoneError);
    emptyUpdate(phoneInput, emptyPhoneError, phoneError);
  }
});

//Email
emailInput.addEventListener("input", () => {
  if (emailVerify(emailInput.value)) {
    emailError.classList.add("hide");
    validInput(emailInput);
  } else {
    errorUpdate(emailInput, emailError);
    emptyUpdate(emailInput, emptyEmailError, emailError);
  }
});

//Password
passwordInput.addEventListener("input", () => {
  if (passwordVerify(passwordInput.value)) {
    passwordError.classList.add("hide");
    validInput(passwordInput);
  } else {
    errorUpdate(passwordInput, passwordError);
    emptyUpdate(passwordInput, emptyPasswordError, passwordError);
  }
});

//Verify password
verifyPasswordInput.addEventListener("input", () => {
  if (verifyPasswordInput.value === passwordInput.value) {
    verifyPasswordError.classList.add("hide");
    validInput(verifyPasswordInput);
  } else {
    errorUpdate(verifyPasswordInput, verifyPasswordError);
    emptyUpdate(passwordInput, emptyVerifyPasswordError, verifyPasswordError);
  }
});

//Submit button
submitButton.addEventListener("click", () => {
  if (validClasses.length == 6 && invalidClasses.length == 0) {
    alert("Success");
  } else {
    alert("Error");
  }
});

That’s it for this tutorial. Our form validation project is now ready. If you face any issues while creating this project you can download the source code by clicking on the ‘Download Code’ button below. I would love to hear from you guys, so if you have any queries, suggestions or feedback you can comment below.
Happy Coding!

Previous articleMCQ – 15/7/22
Next articleMCQ – 17/7/22
RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5 + 6 =

Most Popular