The Wayback Machine - https://web.archive.org/web/20240828023030/https://www.geeksforgeeks.org/form-validation-using-jquery//
Open In App

Form validation using jQuery

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Form validation is a process of confirming the relevant information entered by the user in the input field. In this article, we will be validating a simple form that consists of a username, password, and a confirmed password using jQuery, along with understanding their basic implementation through the examples.

These are the following methods for validation of form using jQuery:

Using plain jQuery

  • First, you need to create an index.html file consisting of an HTML form with username, email, password, and confirm password as input fields.
  • We will use Bootstrap 4 to use Bootstrap’s form controls. At the bottom of the <body> tag, include the “app.js” file having jQuery code for form validation.
  • Create an app.js file that validates the whole form as given below in the code.
  • In the app.js file, when the document is ready, hide all the error messages.
  • Perform the validation task for all the input fields such as username, email, password, and confirm password.

Example 1: This example illustrates the simple form validation using jQuery.

HTML
<!DOCTYPE html>
<html>

<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <!-- jQuery library -->
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <!-- Popper JS -->
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js">
    </script>
    <!-- Latest compiled JavaScript -->
    <script src=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js">
    </script>
</head>

<body>
    <h1 class="text-center text-success">
        Welcome to GeeksforGeeks
    </h1>
    <p class="text-center">
        FORM VALIDATION USING JQUERY
    </p>

    <div class="container">
        <div class="col-lg-8
                    m-auto d-block">
            <form>
                <div class="form-group">
                    <label for="user">
                        Username:
                    </label>
                    <input type="text" 
                           name="username" 
                           id="usernames" 
                           class="form-control">
                    <h5 id="usercheck" 
                        style="color: red;">
                        **Username is missing
                    </h5>
                </div>

                <div class="form-group">
                    <label for="user">
                        Email:
                    </label>
                    <input type="email" 
                           name="email" 
                           id="email" required 
                           class="form-control">
                    <small id="emailvalid" 
                           class="form-text text-muted invalid-feedback">
                        Your email must be a valid email
                    </small>
                </div>

                <div class="form-group">
                    <label for="password">
                        Password:
                    </label>
                    <input type="password" 
                           name="pass" 
                           id="password" 
                           class="form-control">
                    <h5 id="passcheck" 
                        style="color: red;">
                        **Please Fill the password
                    </h5>
                </div>

                <div class="form-group">
                    <label for="conpassword">
                        Confirm Password:
                    </label>
                    <input type="password"
                           name="username" 
                           id="conpassword"
                           class="form-control">
                    <h5 id="conpasscheck" 
                        style="color: red;">
                        **Password didn't match
                    </h5>
                </div>

                <input type="submit"
                       id="submitbtn"
                       value="Submit"
                       class="btn btn-primary">
            </form>
        </div>
    </div>

    <!-- Including app.js jQuery Script -->
    <script src="app.js"></script>
</body>

</html>
JavaScript
$(document).ready(function () {

    // Validate Username
    $("#usercheck").hide();
    let usernameError = true;
    $("#usernames").keyup(function () {
        validateUsername();
    });

    function validateUsername() {
        let usernameValue = $("#usernames").val();
        if (usernameValue.length === "") {
            $("#usercheck").show();
            usernameError = false;
            return false;
        } else if (usernameValue.length < 3 || usernameValue.length > 10) {
            $("#usercheck").show();
            $("#usercheck").html("**length of username must be between 3 and 10");
            usernameError = false;
            return false;
        } else {
            $("#usercheck").hide();
            usernameError = true;
        }
    }

    // Validate Email
    const email = document.getElementById("email");
    let emailError = true;
    email.addEventListener("blur", () => {
        let regex = 
        /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
        let s = email.value;
        if (regex.test(s)) {
            email.classList.remove("is-invalid");
            emailError = true;
        } else {
            email.classList.add("is-invalid");
            emailError = false;
        }
    });

    // Validate Password
    $("#passcheck").hide();
    let passwordError = true;
    $("#password").keyup(function () {
        validatePassword();
    });
    function validatePassword() {
        let passwordValue = $("#password").val();
        if (passwordValue.length === "") {
            $("#passcheck").show();
            passwordError = false;
            return false;
        }
        if (passwordValue.length < 3 || passwordValue.length > 10) {
            $("#passcheck").show();
            $("#passcheck").html(
                "**length of your password must be between 3 and 10"
            );
            $("#passcheck").css("color", "red");
            passwordError = false;
            return false;
        } else {
            $("#passcheck").hide();
            passwordError = true;
        }
    }

    // Validate Confirm Password
    $("#conpasscheck").hide();
    let confirmPasswordError = true;
    $("#conpassword").keyup(function () {
        validateConfirmPassword();
    });
    function validateConfirmPassword() {
        let confirmPasswordValue = $("#conpassword").val();
        let passwordValue = $("#password").val();
        if (passwordValue !== confirmPasswordValue) {
            $("#conpasscheck").show();
            $("#conpasscheck").html("**Password didn't Match");
            $("#conpasscheck").css("color", "red");
            confirmPasswordError = false;
            return false;
        } else {
            $("#conpasscheck").hide();
            confirmPasswordError = true;
        }
    }

    // Submit button
    $("#submitbtn").click(function () {
        validateUsername();
        validatePassword();
        validateConfirmPassword();
        email.dispatchEvent(new Event('blur')); 
        
        if (
            usernameError &&
            passwordError &&
            confirmPasswordError &&
            emailError
        ) {
            return true;
        } else {
            return false;
        }
    });
});

Output:

file

a

Validation using an inbuilt jQuery validation plugin

In this part, you get to know about the inbuilt validation method of jQuery. Create an index.html file and copy the following code.

Example : This example describes the form validation with the help of a built-in jQuery validation plugin.

HTML
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    
    <!-- below we are including the 
         jQuery and jQuery plugin .js files -->
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
      </script>
    <script src=
"https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js">
      </script>
    <script src=
"https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js">
      </script>
    
</head>

<body>
    <form class="cmxform" 
          id="commonForm" 
          method="get" 
          action="form-handler.html"
          autocomplete="off">
        <fieldset>
            <legend>GFG Form</legend>

            <p>
                <label for="cname">
                      Name <span>(required at least 2 character)</span>
                  </label>
              
                <!--User have to set the constraints
                    in attribute form-->
                <input id="cname" 
                       name="name" 
                       minlength="2" 
                       type="text" required>
            </p>
            <p>
                <label for="cemail">
                      Email <span>(required, won't be published)</span>
                  </label>
                <input id="cemail" 
                       type="email" 
                       name="email" required>
            </p>
            <p>
                <label for="curl">
                      URL <span>(Optional)</span>
                  </label>
                <input id="curl" type="url" name="url">
            </p>
            <p>
                <label for="ccomment">
                      Your comment<span>(required)</span>
                  </label>
                <textarea id="ccomment" 
                          name="comment" required>
                  </textarea>
            </p>
            <p>
                <input class="submit" 
                       type="submit" 
                       value="submit">
            </p>
        </fieldset>
    </form>
</body>

</html>
JavaScript
// User have to use id for 
// form and call validate method
$("#commonForm").validate();

Output:

a2


Using jQuery plugins

The jQuery plugins are used to make simpler the code of validation for the clientside. The plugin comes bundled with a useful set of validation methods, including URL and email validation while providing an API to write your own methods. Follow the below example which makes more clarifications regarding it.

Example: This example is the implementation of the above-explained approach.

HTML
<!doctype html>
<html>

<head>
    <meta charset="utf-8">

    <!-- below we are including the jQuery
         and jQuery plugin .js files -->
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
      </script>
    <script src=
"https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js">
      </script>
    <script src=
"https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js">
      </script>
</head>

<body>
    <form class="cmxform" 
          id="signupForm" 
          method="get" 
          action="form-handler.html" 
          autocomplete="off">
        <fieldset>
            <legend>GFG sign-up Form</legend>

            <p>
                <label for="firstname">
                      Firstname
                  </label>
                <input id="firstname" 
                       name="firstname" 
                       type="text">
            </p>
            <p>
                <label for="lastname">
                      Lastname
                  </label>
                <input id="lastname" 
                       name="lastname" 
                       type="text">
            </p>
            <p>
                <label for="username">
                      Username
                  </label>
                <input id="username" 
                       name="username" 
                       type="text">
            </p>
            <p>
                <label for="password">
                      Password
                  </label>
                <input id="password"
                       name="password" 
                       type="password">
            </p>
            <p>
                <label for="confirm_password">
                  Confirm password
                </label>
                <input id="confirm_password" 
                       name="confirm_password" 
                       type="password">
            </p>
            <p>
                <label for="email">
                  Email
                  </label>
                <input id="email" 
                       name="email" 
                       type="email">
            </p>
            <p>
                <label for="agree">
                  Please agree to our policy
                  </label>
                <input id="agree" 
                       name="agree" 
                       type="checkbox">
            </p>
            <p>
                <input class="submit"
                       type="submit" 
                       value="submit">
            </p>

        </fieldset>
    </form>
</body>

</html>
JavaScript
$().ready(function () {

    $("#signupForm").validate({

        // In 'rules' user have to specify all the 
        // constraints for respective fields
        rules: {
            firstname: "required",
            lastname: "required",
            username: {
                required: true,
                minlength: 2 // For length of lastname
            },
            password: {
                required: true,
                minlength: 5
            },
            confirm_password: {
                required: true,
                minlength: 5,

                // For checking both passwords are same or not
                equalTo: "#password"
            },
            email: {
                required: true,
                email: true
            },
            agree: "required"
        },
        // In 'messages' user have to specify message as per rules
        messages: {
            firstname: " Please enter your firstname",
            lastname: " Please enter your lastname",
            username: {
                required: " Please enter a username",
                minlength:
                    " Your username must consist of at least 2 characters"
            },
            password: {
                required: " Please enter a password",
                minlength:
                    " Your password must be consist of at least 5 characters"
            },
            confirm_password: {
                required: " Please enter a password",
                minlength:
                    " Your password must be consist of at least 5 characters",
                equalTo: " Please enter the same password as above"
            },
            agree: "Please accept our policy"
        }
    });
});

 Output:

a3

jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. 

You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.



Similar Reads

Form validation using jQuery Poppa Plugin
In this article, we will learn how to implement form validation using jQuery Poppa plugin. It is a very easy to use, reliable, cross-browser friendly, and lightweight plugin that makes client-side validation very simple. Note: Please download the jQuery Poppa plugin in the working folder and include the required files in the head section of your HT
4 min read
How to create form validation by using only HTML ?
In Web Development, we often use JavaScript with HTML to validate the form, but we can also do the same via HTML in the following ways. HTML &lt;input&gt; required Attribute HTML &lt;input&gt; type Attribute HTML &lt;input&gt; pattern Attribute HTML &lt;input&gt; required Attribute: In input tag of HTML, we can specify via "required attribute". It
2 min read
Form validation using the jbvalidator Plugin
jbvalidator is a jQuery and Bootstrap based plugin which supports both client and server form validations. The provided HTML data attributes are easy to use and understand. The plugin gives multi-language facilities along with custom validation rules and messages. The plugin can be used by downloading the required pre-compiled files from the offici
4 min read
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. We can also check this after submitting the form but it's not recommended. We can easily check before submitting the form this can save us time. In this article, we are
4 min read
ReactJS Form Validation using Formik and Yup
ReactJS Form Validation using Formik and Yup packages is one good approach for form validation. we can validate forms using controlled components. But it may be time-consuming and the length of the code may increase if we need forms at many places on our website. Formik is designed to manage forms with complex validation with ease. Formik supports
3 min read
Validation of file size while uploading using JavaScript / jQuery
Validation of file size while uploading is important to provide a nice user experience. In this article, we will learn how to implement file size validation by checking file size before uploading using JavaScript and jQuery. Below are both the ways: Table of Content Using JavaScriptUsing jQueryApproach 1: Using JavaScriptListen for the change event
2 min read
Twitter Like Character Count Validation using jQuery
In this article, we will create a web app that mimics the character count validation behavior of Twitter (X). When users start typing in a textarea, the number of characters and a progress bar will appear below the textarea. This basically displays the remaining character count as well as limiting the max length of input text, by using jQuery. Appr
3 min read
AngularJS Form Validation
AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not. Form input fields have the following states: $untouched: It sho
3 min read
Form required attribute with a custom validation message in HTML5
The creation of web forms has perpetually been a fancy task. whereas marking up the shape itself is simple, checking whether or not every field features a valid and coherent price is tougher, and informing the user concerning the matter might become a headache. HTML5 introduced new mechanisms for forms. There 2 kinds of Constraint Validation DOM Me
4 min read
Spectre Forms Form validation styles
Spectre Forms validation styles class is used to style the form. To use form validation styles, you can either add is-success or is-error class to the controls. Add has-success or has-error class to parent elements. Use the form-input-hint class to provide form validation success and error messages. Forms Form validation styles Classes: is-success:
2 min read
Primer CSS Form Group Validation
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
3 min read
React Suite Form Validation Default Check
React Suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we’ll learn about React Suite Form Validation Default Check. A form is a set of components and mod
3 min read
React.js Chakra UI Form Validation
Chakra UI is a simple and effective component-based library, that allows developers to build modern and attractive UI's for their website's frontends. Developers can simply use the components pre-defined in Chakra UI in their React.js Code to work faster and write less. The best part of Chakra UI is its reusability since it's a component-based libr
5 min read
React Suite Components Form validation
React Suite is a front-end library, containing a wide range of React Components used in enterprise applications. This article discusses how the React suite's Form Validation helps developers add validation to forms. Form Validation involves providing prompt information to the user when there is an error in the data entered with the form. Form valid
7 min read
What is the purpose of controlled components in form validation?
Controlled components in form validation are like friendly assistants that help you keep track of what's happening in your form. Imagine them as little helpers who hold onto all the information you put into each input field. They ensure that every time you type something or change an entry, they carefully update and remember it for you. This not on
2 min read
Explain the use of the yup library for form validation.
The 'yup' library is a JavaScript library commonly used for schema validation, particularly in the context of form validation. Yup helps validate data against a predefined schema. It's often used in JavaScript applications, especially those built with frameworks like React, to ensure that the data entered into forms meets certain criteria or rules.
2 min read
PHP Form Validation
Form validation is a crucial step that needs to be completed before submitting data to the database. This process is performed to prevent any errors or faulty data from being inserted into the database. The HTML form includes various input fields such as email, text, checkbox, radio button, etc. These input fields must be validated to ensure that t
7 min read
How to Create a Bootstrap Form Validation ?
A Bootstrap Form Validation ensures that user input complies with established standards before submission, improves the user experience, and minimizes server-side processing for incorrect inputs. We can add client-side validation to their forms by using two different methods including Bootstrap built-in classes and JavaScript. Table of Content Usin
3 min read
How To Implement NextJS Form Validation With Formik And Zod ?
Form validation is a critical aspect of web development to ensure that user input meets specific criteria before submitting data to the server. Implementing form validation in Next.js can be simplified using Formik, a form library for React, and Zod, a schema validation library. Together, they provide a robust solution for managing form state and v
3 min read
React Bootstrap Form Validation
In Web Application Development, React-Bootstrap is the framework that helps to develop web pages in a more attractive form. While developing the application, we designed input fields and forms that need to be validated to maintain security. So, we can do this by using React Bootstrap Form Validation. In this article, we will see the Syntax, Propert
3 min read
How to perform form validation for a required field in HTML ?
The form data is very important for a website and the correct form data or valid form data must be submitted to the form. To make sure that the form data is valid or to make an input field mandatory, various attributes can be used. We shall discuss the following attributes in this article &amp; will understand them with the help of examples.  Table
5 min read
How to prevent form submission when input validation fails in AngularJS ?
Validation of fields is an important process while developing a dynamic web application. In terms of security, validation is an important concept. We pass the data from the client side through input fields to the server. If any of the fields is not validated properly and the user sends any irrelevant data then there can be cause of different securi
7 min read
React Suite Components Form validation Input
React Suite is a collection of beautiful and customizable components for ReactJS that makes building user interfaces easier. One essential component is the Input. It handles form validation and user input smoothly, showing helpful error messages. This makes it perfect for creating strong and user-friendly web apps. Form validation inputThe Input co
3 min read
How to perform form validation in React?
Form validation in React involves ensuring that the data entered into a form meets certain criteria before submission. In this, we will see the form validation in React. Pre-requisitesNodeJS and NPMReactJSReact useState hookHTML, CSS, and JavaScriptSteps to Create React Application And Installing ModuleStep 1: Create a React application using the f
4 min read
How to Implement Form Validation in React Native ?
React Native is a JavaScript framework for cross-platform mobile app development. Expo CLI simplifies React Native development with a streamlined process and helpful tools. In this article, we'll see how to implement form validation in react native. Form validation ensures the validity of user input by checking against specific rules or constraints
3 min read
How to Add Form Validation In Next.js ?
Forms play a crucial role in modern web applications by ensuring the accuracy and validity of data. Ne­xt.js, a versatile framework for building Re­act applications, offers form validation that helps verify use­r input against predefined crite­ria, provides immediate feedback, and enhances data quality. In this article, we will cover essential conc
3 min read
JavaScript Form Validation
JavaScript Form Validation is a way to ensure that the data users enter into a form is correct before it gets submitted. This helps ensure that things like emails, passwords, and other important details are entered properly, making the user experience smoother and the data more accurate. Steps for Form Validation in JavaScriptWhen we validate a for
6 min read
What is Unobtrusive Validation in jQuery?
jQuery is a Javascript library. An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side. Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side vali
2 min read
How to check validation of IP Address in jQuery ?
In this article, we will find how to validate the IP Address using jQuery. IP Address: Every computer connected to the Internet is identifiable by a unique string, which is known as its Internet Protocol (IP) address. It consists of four numbers (each between 0 and 255) separated by dots. The format of an IP address can be written as four decimal n
2 min read
How to submit a form or a part of a form without a page refresh using jQuery?
How to prevent an HTML form to submit?When submitting a form, clicking the submit button usually navigates to a new route as specified in the form's action attribute. However, this can be done in the background using event.preventDefault(), which blocks the default event behavior. By attaching an onsubmit event listener to the form, we can prevent
2 min read