Form validation using jQuery

Form validation is a process of confirming the relevant information entered by the user in the input field. Here we will be validating a simple form that consists of a username, password and a confirm password using jQuery.

Prerequisites: You must be aware of the basics of HTML, CSS, JavaScript, and jQuery.

Approach:

  1. First of all, you need to create an index.html file that consists of Bootstrap 4 form with username, email, password, and confirm password as input fields. At the bottom of the “body” tag, include the “app.js” file having jQuery code for form validation.
  2. Create an app.js file that validates the whole form as given below in the code.
  3. 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.

index.html: The following HTML code demonstrates the form design for user input.

HTML



filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
<head>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href=
     4.0.0/css/bootstrap.min.css">
    <!-- jQuery library -->
    <script src=
     jquery/3.3.1/jquery.min.js">
    </script>
    <!-- Popper JS -->
    <script src=
     popper.js/1.12.9/umd/popper.min.js">
    </script>
    <!-- Latest compiled JavaScript -->
    <script src=
     4.0.0/js/bootstrap.min.js">
    </script>
</head>
  
<body><br>
    <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>

chevron_right


app.js: The following jQuery code for validation is used in the above HTML file .

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Document is ready
$(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();
      }
    }
  
   // Validate Email
    const email = 
        document.getElementById('email');
    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 passwrdValue = 
            $('#password').val();
        if (passwrdValue.length == '') {
            $('#passcheck').show();
            passwordError = false;
            return false;
        
        if ((passwrdValue.length < 3)|| 
            (passwrdValue.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();
        }
    }
          
// Validate Confirm Password
    $('#conpasscheck').hide();
    let confirmPasswordError = true;
    $('#conpassword').keyup(function () {
        validateConfirmPasswrd();
    });
    function validateConfirmPasswrd() {
        let confirmPasswordValue = 
            $('#conpassword').val();
        let passwrdValue = 
            $('#password').val();
        if (passwrdValue != confirmPasswordValue) {
            $('#conpasscheck').show();
            $('#conpasscheck').html(
                "**Password didn't Match");
            $('#conpasscheck').css(
                "color", "red");
            confirmPasswordError = false;
            return false;
        } else {
            $('#conpasscheck').hide();
        }
    }
      
// Submitt button
    $('#submitbtn').click(function () {
        validateUsername();
        validatePassword();
        validateConfirmPasswrd();
        validateEmail();
        if ((usernameError == true) && 
            (passwordError == true) && 
            (confirmPasswordError == true) && 
            (emailError == true)) {
            return true;
        } else {
            return false;
        }
    });
});

chevron_right


Output: Below is the output generated when the user directly hits the submit button.

Below is the output generated when the user enters invalid details in the form.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.