Form Validation using HTML, CSS & JavaScript

Form Validation using HTML, CSS & JavaScript

Form Validation using HTML, CSS & JavaScript

Introduction

Hello, today we’re going to learn how to use HTML, CSS & JavaScript to create a Form Validation. By following these instructions, you can simply make this Form Validation in HTML, CSS & JavaScript. Simply by adhering to the procedures mentioned below, you will be able to develop this amazing Form Validation.

Form Validation Using Javascript

Let us understand how an Form Validation contributes, Earlier when we used to fill up the form there was no check or verification on the input to see whether the details belong to the user itself or it is fake or stolen from someone. So to make it authenticate or see whether the input is correct or not we will see the use of form validator in this project.

Project Description

Step 1
The HTML (Hypertext Markup Language) will help us to create the structure for the list with some necessary attributes and elements to make Form Validation Project.

Step 2
Then we will use CSS (Cascading Stylesheet) which will help us to style or design the project with suitable padding and alignment in the Form Validation Project.

Portfolio Website using HTML and CSS (Source Code)

Step 3
At last we will use JS (JavaScript) which will add a logic to make the Form Validation Project functioning from the user end.

I hope you have got an idea about the project.

HTML Code for Form Validation

<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">Sign Up</button>
      </form>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

First we’ll start with creating the structure of the Form Validation project for that as you can see the above code we have used all the necessary elements & attributes to setup the structure. Let us know code the CSS part to add styling and aligned the tags.

CSS Code for Form Validation

* {
  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;
  }
}

Second comes the CSS code, which is mentioned above in that we have styled for the structure we have padded as well as aligned the Form Validation project so that it is properly situated and doesn’t get messy with suitable CSS elements. Now we have created the structure using HTML and styled the webpage using CSS its time to add the functionality using JavaScript in this project.

50+ HTML, CSS & JavaScript Projects With Source Code

JavaScript Code for Form Validation

//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");
  }
});

Last stage of the project the JavaScript in which we have added the logical and coded as per the requirement with some conditions. In this code each input is defined which is built in the HTML code and given a name so that it can be called in terms of JavaScript. In the verification part we have defined when to show the message to validate each field. Let us see the Final Output of the project Form Validation using HTML, CSS & JavaScript (Source Code).

Output

Live Preview of Form Validation using HTML, CSS & JavaScript

See the Pen
Form
by Harsh Sawant (@harshh9)
on CodePen.

We have Successfully created our Form Validation using HTML, CSS & JavaScript (Source Code). You can use this project for your personal needs and the respective lines of code are given with the code pen link mentioned above.

If you find out this Blog helpful, then make sure to search code with random on google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

Code Idea – codingartist

Written By – Harsh Sawant

Code By – @harshh9



Leave a Reply