Open In App

Form Validation using JavaScript

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Form validation refers to the process of ensuring that user input submitted through a form meets certain criteria or constraints before it is accepted and processed by a computer system.

The data entered into a form needs to be in the right format and certain fields need to be filled in to effectively use the submitted form. Username, password, and contact information are some details that are mandatory in forms and thus need to be provided by the user.

Form Validation Approach in JavaScript:

Here, we have used includes method to check for validations. The includes() function is used to check whether the passed string is contained by the testing string or not which can also be used to validate the form.

Form Validation JavaScript Example:

Here, Form Validation is done using JavaScript includes() method.

Javascript




function GEEKFORGEEKS() {
    const name =
        document.forms.RegForm.Name.value;
    const email =
        document.forms.RegForm.EMail.value;
    const what =
        document.forms.RegForm.Subject.value;
    const password =
        document.forms.RegForm.Password.value;
    const address =
        document.forms.RegForm.Address.value;
  
    console.log(name, email, what, password, address);
  
    if (name === ""
        || name.includes('0') || name.includes('1')
        || name.includes('2') || name.includes('3')
        || name.includes('4') || name.includes('5')
        || name.includes('6') || name.includes('7')
        || name.includes('8') || name.includes('9')) {
        window.alert
            ("Please enter your name properly.");
        name.focus();
        return false;
    }
  
    if (address === "") {
        window.alert
            ("Please enter your address.");
        address.focus();
        return false;
    }
  
    if (email === "" || !email.includes('@')) {
        window.alert
            ("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
  
    if (password === "") {
        alert("Please enter your password");
        password.focus();
        return false;
    }
  
    if (password.length < 6) {
        alert
            ("Password should be atleast 6 character long");
        password.focus();
        return false;
  
    }
  
    if (what.selectedIndex === -1) {
        alert("Please enter your course.");
        what.focus();
        return false;
    }
  
    return true;
}


HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>
        Form validation using HTML
        and JavaScript
    </title>
    <style>
        div {
            box-sizing: border-box;
            width: 100%;
            border: 100px solid black;
            float: left;
            align-content: center;
            align-items: center;
        }
  
        form {
            margin: 0 auto;
            width: 600px;
        }
    </style>
</head>
  
<body>
    <h1 style="text-align: center;">
        REGISTRATION FORM
    </h1>
    <form name="RegForm" 
          onsubmit="return GEEKFORGEEKS()">
        <p>
            Name:
            <input type="text" size="65" 
                   name="Name" 
                   placeholder="GeeksforGeeks"/>
        </p>
        <br />
        <p>
            Address:
            <input type="text" size="65" 
                   name="Address" 
                   placeholder="Bangalore, Karnataka"/>
        </p>
        <br />
        <p>
            E-mail Address:
            <input type="text" size="65" 
                   name="EMail" 
                   placeholder="demo@example.com"/>
        </p>
        <br />
        <p>
            Password:
            <input type="password" size="65" 
                   name="Password" />
        </p>
        <br />
        <br />
        <p>
            Select Your Course: 
            <select value="" name="Subject">
                <option>Select Course</option>
                <option>BTECH</option>
                <option>BBA</option>
                <option>BCA</option>
                <option>B.COM</option>
            </select>
        </p>
        <br />
        <br />
        <p>
            Comments:
            <textarea cols="55" name="Comment"> </textarea>
        </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>


Output:

Form Validation JavaScript Example Output

Form Validation JavaScript Example Explanation:

  1. The code gets the values of various form fields (name, email, what, password, address) using document.forms.RegForm.
  2. Data Validation:
    • Name Validation: Checks if the name field is empty or contains any digits.
    • Address Validation: Checks if the address field is empty.
    • Email Validation: Checks if the email field is empty or lacks the ‘@’ symbol.
    • Password Validation: Checks if the password field is empty or less than 6 characters long.
    • Course Selection Validation: Checks if a course is selected.
  3. Error Handling:
    • Displays alerts if any of the fields fail validation criteria.
    • Sets focus back to the respective field.
  4. Returns true if all validation checks pass, indicating that the form can be submitted. Otherwise, it returns false, preventing form submission.
  5. Sets focus to the first field that failed validation, ensuring the user’s attention is drawn to the problematic field.

Form Validation in JavaScript – Use case:

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

1. Form validation using jQuery

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

2. Number validation in JavaScript

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.

3. Password Validation Form Using JavaScript

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. 

4. How to validate confirm password using JavaScript ?

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

5. JavaScript Program to Validate Password using Regular Expressions

A 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.

Note: We can also use Regular expression for form validation. The regular expression can be used to validate the email, password, name, or any other field in the form by defining a particular Regex for each field. You can check how to validate form using Regular Expression in JavaScript here.



Last Updated : 19 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads