Form Validation in JavaScript

0

Hey everyone hope you are all fine, today we are going to learn Form Validation in JavaScript. Form validation plays a crucial role in ensuring that user input is accurate, complete, and meets specific criteria.

JavaScript, being a versatile programming language, provides powerful tools and techniques for validating forms on the client side. In this article, we will explore the concept of form validation in JavaScript and discuss various strategies for implementing it effectively.

Why Form Validation?

Form validation is essential for maintaining data integrity and improving the overall user experience. By validating user input before submitting it to the server, we can prevent errors, ensure data consistency, and provide meaningful feedback to users, reducing the chances of incorrect or incomplete data being processed.

Common Validation Techniques:

JavaScript offers several techniques for validating form inputs. Here are some commonly used methods:

  1. Required Fields: One of the simplest forms of validation is checking whether certain fields are required. This ensures that users provide the necessary information before submitting the form.
  2. Data Format Validation: Validation can involve verifying that the entered data matches a specific format, such as email addresses, phone numbers, or dates. Regular expressions are often employed to perform pattern matching and enforce format requirements.
  3. Numeric and Range Validation: For numeric inputs, validation can include checking if the entered value is a number, within a certain range, or meets other numerical criteria.
  4. Password Strength Validation: When dealing with password inputs, it is important to enforce certain complexity requirements, such as a minimum length, and the inclusion of uppercase letters, lowercase letters, numbers, or special characters. JavaScript can assist in validating and providing feedback on the strength of passwords.
  5. Custom Validation: In some cases, you may need to apply custom validation logic based on specific business rules or requirements. JavaScript allows you to implement custom validation functions to suit your needs.

Form Validation Strategies:

To implement form validation effectively, consider the following strategies:

  1. Event Handling: Leverage JavaScript event-handling mechanisms, such as the submit event, to intercept form submission and perform validation checks before allowing the form to be sent to the server.
  2. Error Messaging: Provide clear and concise error messages that inform users about validation failures. Display these messages near the corresponding form fields, preferably in a prominent and noticeable manner.
  3. Visual Feedback: Visually indicate invalid fields by applying CSS styles, such as borders or highlighting, to help users easily identify and correct their input.
  4. Progressive Validation: Consider implementing progressive validation, where form fields are validated as users enter data, providing real-time feedback. This approach can help users identify and fix errors immediately, improving the overall form-filling experience.

Form Validation in JavaScript

Let’s look at that practically, I’ve made the complete tutorial you need to watch it. Inside the tutorial, you will learn everything step by step from scratch.

Hope this tutorial is helpful and beneficial for you, I’m going to share with you the complete source code that I’ve used inside the video tutorial. Let’s look at that the source code.

You May Also Like:

<!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 in JavaScript</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <!-- --------------------signup form start--------------- -->
    <section class="form_validation">
      <h2>Signup Form</h2>
      <form action="/" id="form">
        <div class="input_data">
          <input
            type="text"
            class="form_control username"
            placeholder="User Name"
          />
          <div class="error"></div>
        </div>
        <div class="input_data">
          <input
            type="text"
            class="form_control useremail"
            placeholder="User Email"
          />
          <div class="error"></div>
        </div>
        <div class="input_data">
          <input
            type="password"
            class="form_control password"
            placeholder="Password"
          />
          <div class="error"></div>
        </div>
        <div class="input_data">
          <input
            type="password"
            class="form_control cpassword"
            placeholder="Confirm Password"
          />
          <div class="error"></div>
        </div>
        <button type="submit">Signup</button>
      </form>
    </section>
    <!-- --------------------signup form close--------------- -->

    <script src="js/script.js"></script>
  </body>
</html>

It’s index.html The file inside the file has an HTML structure that is used to display the input field, button, etc. Once you used it inside the project, then you need to use a CSS file to design it.

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

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

body {
  background: #6495ed;
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  font-family: "ruda", "poppins";
}

.form_validation {
  padding: 2rem;
  background: #ecf0f1;
  max-width: 450px;
  width: 100%;
  border-radius: 5px;
  box-shadow: 5px 10px 5px rgba(0, 0, 0, 0.5);
}

.form_validation h2 {
  font-size: 2rem;
  padding: 1rem 0 2rem 0;
}

.form_control {
  width: 100%;
  padding: 0.85rem 0.8rem;
  border-radius: 5px;
  border: none;
  outline: none;
  font-size: 0.9rem;
}

.form_validation button {
  display: block;
  outline: none;
  background: #e74c3c;
  color: #fff;
  cursor: pointer;
  border: none;
  padding: 0.6rem 2rem;
  border-radius: 4px;
  margin: 1rem 0;
  font-size: 1rem;
}

.error {
  display: block;
  color: red;
  padding: 0.4rem 0 1rem 0.2rem;
}

/* After Adding the Class */
.input_data.errormsg .form_control {
  border: 1px solid red;
}

.input_data.success .form_control {
  border: 1px solid green;
}

It’s style.css that are used to design the signup form. You need to use the same code inside the project, If you have an idea about CSS, then you can change the design as you want.

"use strict";

const form = document.getElementById("form");
const userName = document.querySelector(".username");
const userEmail = document.querySelector(".useremail");
const userPass = document.querySelector(".password");
const usercPass = document.querySelector(".cpassword");

form.addEventListener("submit", (e) => {
  e.preventDefault();
  validInput();
});

// ----------------Step 2-------------------
const showError = (ele, msg) => {
  const inputControl = ele.parentElement;
  const errormsg = inputControl.querySelector(".error");
  errormsg.innerText = msg;
  inputControl.classList.add("errormsg");
};

// ----------------Step 3-------------------
const setSuccess = (ele) => {
  const inputControl = ele.parentElement;
  const errormsg = inputControl.querySelector(".error");
  errormsg.innerText = "";
  inputControl.classList.remove("errormsg");
  inputControl.classList.add("success");
};

// ----------------Step 4-------------------
const isvalidEmail = (email) => {
  const reTest =
    /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
  return reTest.test(String(email).toLowerCase());
};

// ----------------Step 1-------------------
const validInput = () => {
  const userEl = userName.value.trim();
  const emailEl = userEmail.value.trim();
  const passEl = userPass.value.trim();
  const passcEl = usercPass.value.trim();

  // user name validation
  if (userEl === "") {
    showError(userName, "Please Enter User Name!");
  } else {
    setSuccess(userName);
  }

  // email validation
  if (emailEl === "") {
    showError(userEmail, "Please Enter User Email!");
  } else if (!isvalidEmail(emailEl)) {
    showError(userEmail, "Please Enter Valid Email");
  } else {
    setSuccess(userEmail);
  }

  // password validation
  if (passEl === "") {
    showError(userPass, "Please Enter Password!");
  } else if (passEl.length < 8) {
    showError(userPass, "Password must be at least 8 characters!");
  } else {
    setSuccess(userPass);
  }

  // confirm password
  if (passcEl === "") {
    showError(usercPass, "Please Enter Confrim Password!");
  } else if (passEl !== passcEl) {
    showError(usercPass, "Password Dosn't Match!");
  } else {
    setSuccess(usercPass);
  }
};

Finally, You need to JS code inside the project that is used to add the validation inside the input fields. I hope this tutorial is helpful and beneficial for you.

Conclusion:

Form validation in JavaScript is a fundamental aspect of creating robust and user-friendly web forms. By implementing appropriate validation techniques and strategies, you can ensure the accuracy and integrity of user-submitted data.

JavaScript provides a flexible and powerful toolkit for performing form validation, enabling you to enhance user experience and streamline data submission processes on the client side.

Remember, while client-side validation is important for improving user experience, server-side validation should always be implemented to ensure the security and integrity of data.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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