JavaScript Form Validation

JavaScript Form Validation ensures data integrity by verifying user input before submission. It validates fields like passwords, emails, and selections, providing alerts for invalid data, and enhancing user experience and data accuracy.

Approach for Form Validation in JavaScript

In this approach, we are following these steps

  • Data Retrieval: It retrieves the values of various form fields like name, email, course selection, password, and address using document.forms.RegForm.
  • Data Validation:
    • Name Validation: Checks if the name field is empty or contains any digits.
    • Address Validation: Ensures the address field is not empty.
    • Email Validation: Verifies if the email field is not empty and contains the ‘@’ symbol.
    • Password Validation: Validates that the password field is not empty and has a minimum length of 6 characters.
    • Course Selection Validation: Ensures that a course is selected from the dropdown.
  • Error Handling:
    • If any of the validation criteria fail, it displays an alert message using window.alert.
    • Sets focus back to the respective field that failed validation, ensuring the user’s attention is drawn to the problematic field.
  • Submission Control:
    • Returns true if all validation checks pass, indicating that the form can be submitted. Otherwise, it returns false, preventing form submission.
  • Focus Adjustment:
    • Sets focus to the first field that failed validation, ensuring the user’s attention is drawn to the problematic field.

Example: Here is an example of above explained approach.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0" />
    <title>Form Validation</title>
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <h1>REGISTRATION FORM</h1>
    <form name="RegForm" onsubmit="return validateForm()">
        <p>
            <label for="name">Name:</label>
            <input type="text" id="name" name="Name" 
                placeholder="Enter your full name" />
            <span id="name-error" class="error-message"></span>
        </p>
        <p>
            <label for="address">Address:</label>
            <input type="text" id="address" name="Address" 
                placeholder="Enter your address" />
            <span id="address-error" class="error-message"></span>
        </p>
        <p>
            <label for="email">E-mail Address:</label>
            <input type="text" id="email" name="EMail" 
                placeholder="Enter your email" />
            <span id="email-error" class="error-message"></span>
        </p>
        <p>
            <label for="password">Password:</label>
            <input type="password" id="password" name="Password" />
            <span id="password-error" class="error-message"></span>
        </p>
        <p>
            <label for="subject">Select Your Course:</label>
            <select id="subject" name="Subject">
                <option value="">
                    Select Course
                </option>
                <option value="BTECH">
                    BTECH
                </option>
                <option value="BBA">
                    BBA
                </option>
                <option value="BCA">
                    BCA
                </option>
                <option value="B.COM">
                    B.COM
                </option>
            </select>
            <span id="subject-error" class="error-message"></span>
        </p>
        <p>
            <label for="comment">College Name:</label>
            <textarea id="comment" name="Comment"></textarea>
        </p>
        <p>
            <input type="checkbox" id="agree" name="Agree" />
            <label for="agree">I agree to the above
                information</label>
            <span id="agree-error" class="error-message"></span>
        </p>
        <p>
            <input type="submit" value="Send" name="Submit" />
            <input type="reset" value="Reset" name="Reset" />
        </p>
    </form>
    <script src="script.js"></script>
</body>

</html>
CSS
body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
}

h1 {
    text-align: center;
    color: #333;
}

form {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

input[type="text"],
input[type="password"],
select,
textarea {
    width: 100%;
    padding: 10px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
    font-size: 16px;
}

select {
    width: 100%;
    padding: 10px;
    margin: 5px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
    font-size: 16px;
    background-color: #fff;
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
}

textarea {
    resize: vertical;
}

input[type="submit"],
input[type="reset"],
input[type="checkbox"] {
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    cursor: pointer;
    font-size: 16px;
}

input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="checkbox"]:hover {
    background-color: #0056b3;
}

.error-message {
    color: red;
    font-size: 14px;
    margin-top: 5px;
}
JavaScript
function validateForm() {
    const name = document.getElementById("name").value;
    const address = document.getElementById("address").value;
    const email = document.getElementById("email").value;
    const password = document.getElementById("password").value;
    const subject = document.getElementById("subject").value;
    const agree = document.getElementById("agree").checked;
    const nameError = document.getElementById("name-error");
    
    const addressError = document.getElementById(
        "address-error"
    );
    const emailError = document.getElementById(
        "email-error"
    );
    const passwordError = document.getElementById(
        "password-error"
    );
    const subjectError = document.getElementById(
        "subject-error"
    );
    const agreeError = document.getElementById(
        "agree-error"
    );

    nameError.textContent = "";
    addressError.textContent = "";
    emailError.textContent = "";
    passwordError.textContent = "";
    subjectError.textContent = "";
    agreeError.textContent = "";

    let isValid = true;

    if (name === "" || /\d/.test(name)) {
        nameError.textContent =
            "Please enter your name properly.";
        isValid = false;
    }

    if (address === "") {
        addressError.textContent =
            "Please enter your address.";
        isValid = false;
    }

    if (email === "" || !email.includes("@")) {
        emailError.textContent =
            "Please enter a valid email address.";
        isValid = false;
    }

    if (password === "" || password.length < 6) {
        passwordError.textContent =
            "Please enter a password with at least 6 characters.";
        isValid = false;
    }

    if (subject === "") {
        subjectError.textContent =
            "Please select your course.";
        isValid = false;
    }

    if (!agree) {
        agreeError.textContent =
            "Please agree to the above information.";
        isValid = false;
    }

    return isValid;
}

Output:

JavaScript Form Validation Example Output


Types of Form Validation

  • Client-side validation: JavaScript is typically used to validate forms on the user’s browser before submission. This provides immediate feedback to users and prevents unnecessary server requests.
  • Server-side validation: Even with client-side validation, it’s crucial to re-validate form data on the server-side. This reduce any potential issues that might arise due to disabled JavaScript or browser manipulation.

Various Use case

Below are the some use cases of Form Validation in JavaScript.

Here, we have validated a simple form that consists of a username, password, and a confirmed password using jQuery, 

Sometimes the data entered into a text field needs to be in the right format and must be of a particular type in order to effectively use the form. For instance, Phone number, Roll number, etc are some details that must be in digits not in the alphabet.

The password Validation form is used to check the password requirements such as the password must have at least one Uppercase, or lowercase, number, and the length of the password. 

You can validate a confirm password field using JavaScript by comparing it with the original password field.

Regular Expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text to replace operations. A regular expression can be a single character or a more complicated pattern.



Contact Us