Client-side Form Validation using JavaScript


Form validation in JavaScript is a process of ensuring that the data entered into a form by the user is valid and meets certain criteria or requirements. This is typically done before the form is submitted to the server, and is often referred to as client-side validation.

JavaScript provides various methods for validating form inputs, including regular expressions and built-in methods such as isNaN() and isFinite(). By using these methods, developers can check that the input matches a certain pattern, is within a certain range, or meets other specific criteria.

To implement form validation in JavaScript, developers can attach event listeners to the form's input elements, such as text boxes and radio buttons. When the user interacts with these elements, the event listener can check the input value and determine whether it meets the specified criteria. If the input is invalid, the listener can display an error message to the user.

It is important to note that form validation in JavaScript is a form of client-side validation, which means that it can be bypassed or manipulated by malicious users. Therefore, it should always be used in conjunction with server-side validation to ensure the security and integrity of the data submitted by the user.

This is a JavaScript code that implements form validation on a web page.

Source Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form Validation</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <div class="container">
      <form action="#" id="form" class="form" autocomplete="off">
        <h3>Registration Form</h3>

        <div class="form-group">
          <label for="username">User Name</label>
          <input type="text" id="username" data-name="User Name" placeholder="Enter User Name" />
          <p>Error Message</p>
        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input type="text" id="email" data-name="Email Id" placeholder="Enter Email Id" />
          <p>Error Message</p>
        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input type="password" id="password" placeholder="Enter password" data-name="Password" />
          <p>Error Message</p>
        </div>
        <div class="form-group">
          <label for="password2">Confirm Password</label>
          <input type="password" id="password2" placeholder="Enter Confirm Password" data-name="Confirm Password" />
          <p>Error Message</p>
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
    <script src="js/script.js"></script>
  </body>
</html>

css/style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;800&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  width: 100vw;
  height: 100vh;
  background-color: palegreen;
  display: grid;
  place-items: center;
}

.container {
  background-color: #fff;
  width: 500px;
  padding: 10px;
  border-radius: 3px;
}

.container h3 {
  font-weight: 500;
  text-align: center;
  text-transform: uppercase;
  margin-bottom: 20px;
}
.form {
  padding: 30px 40px;
}
.form-group {
  color: #333;
  margin-bottom: 5px;
  padding-bottom: 10px;
}
.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #3c40c6;
  font-weight: 500;
}
.form-group input {
  border: 2px solid #aaa;
  width: 100%;
  padding: 10px;
  font-size: 14px;
  outline: none;
  border-radius: 3px;
}

.form-group p {
  font-size: 11px;
  margin-top: 5px;
  visibility: hidden;
}

.form button {
  width: 100%;
  padding: 10px;
  border: 2px solid #3c40c6;
  color: #fff;
  background-color: #3c40c6;
  text-transform: uppercase;
  font-weight: 500;
  border-radius: 3px;
}

.form-group.error p {
  color: #f53b57;
  visibility: visible;
}

.form-group.error input {
  border-color: #f53b57;
}

.form-group.success input {
  border-color: #05c46b;
}

js/script.js

const form = document.getElementById("form");
const username = document.getElementById("username");
const email = document.getElementById("email");
const password = document.getElementById("password");
const password2 = document.getElementById("password2");

String.prototype.isEmail = function () {
  return !!this.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/);
};

String.prototype.isAlpha = function () {
  return !!this.match(/^[a-zA-Z]*$/);
};

function checkRequired(inputs) {
  inputs.forEach((input) => {
    if (input.value.trim() === "") {
      //Error
      errorInput(input, `${getName(input)} is Required`);
    } else {
      //Success
      successInput(input);
    }
  });
}
function getName(input) {
  //return input.id;
  return input.getAttribute("data-name");
}
function errorInput(input, message) {
  const formGroup = input.parentElement;
  formGroup.className = "form-group error";
  const p = formGroup.querySelector("p");
  p.innerHTML = message;
}
function successInput(input) {
  const formGroup = input.parentElement;
  formGroup.className = "form-group success";
  const p = formGroup.querySelector("p");
  p.innerHTML = "";
}

function checkLength(input, min, max) {
  const data = input.value.trim().length;
  if (data < min) {
    errorInput(input, `${getName(input)} must be aleast greater than ${min} characters`);
  } else if (data > max) {
    errorInput(input, `${getName(input)} must be aleast lesser than ${max} characters`);
  } else {
    successInput(input);
  }
}

function checkConfirmPassword(password, password2) {
  if (password.value != password2.value) {
    errorInput(password2, `${getName(password2)}  does not match`);
  }
}

function checkEmail(input) {
  if (!input.value.trim().isEmail()) {
    errorInput(input, `This is not an valid email address`);
  }
}
function checkAlpha(input) {
  if (!input.value.trim().isAlpha()) {
    errorInput(input, `${getName(input)}  Must be Alphabets`);
  }
}

form.addEventListener("submit", function (e) {
  e.preventDefault();
  checkRequired([username, email, password, password2]);
  checkLength(username, 5, 10);
  checkLength(password, 5, 10);
  checkConfirmPassword(password, password2);
  checkEmail(email);
  checkAlpha(username);
});

It first declares variables for the form element and various input elements (username, email, password, and password2), which are obtained using the getElementById method.

Next, it extends the String object by adding two prototype methods: isEmail and isAlpha. The isEmail method checks whether a string represents a valid email address, while the isAlpha method checks whether a string contains only alphabetic characters.

The checkRequired function is used to check whether any of the input fields are empty. If an input field is empty, it displays an error message using the errorInput function. If it is not empty, it displays a success message using the successInput function.

  • The getName function returns the name of an input field, which is used in error messages.
  • The errorInput function adds an "error" class to the parent element of an input field, and displays an error message.
  • The successInput function adds a "success" class to the parent element of an input field, and clears the error message.
  • The checkLength function checks the length of a string, and displays an error message if the length is outside a specified range.
  • The checkConfirmPassword function checks whether the password and confirm password fields match, and displays an error message if they do not match.
  • The checkEmail function uses the isEmail prototype method to check whether an email address is valid, and displays an error message if it is not.
  • The checkAlpha function uses the isAlpha prototype method to check whether a username contains only alphabetic characters, and displays an error message if it does not.

Finally, the code attaches an event listener to the form element for the "submit" event. When the form is submitted, it prevents the default behavior (i.e., submitting the form to the server), and runs all the validation functions to ensure that the form inputs are valid.

Output

Form Validation

Live Preview


List of Programs


JS Practical Questions & Answers


JS Practical Project