Form validation using jQuery

This tutorial shows, how to validate a basic form with jQuery without jQuery Plugin?
In this tutorial, we will check that:
  • The name field has been filled out.
  • The email address field looks like an email address.

Step 1: Include jQuery

First, we need to include the jQuery library from below link. https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js

Step 2: Create Html Form

We will create two input fields, one is for Name and other for Email Address. <form action="" id="quoteForm"> <div class="form-group"> <label for="name">Your Name *:</label> <input type="text" class="form-control" id="name" name="name"> </div> <div class="form-group"> <label for="email">Email address:</label> <input type="email" class="form-control" name="email"> </div> <button id="quoteSubmit" type="button" class="btn btn-default">Submit</button> </form>

Step 3: Insert jQuery Code

On Button Click we call checkQuoteFrm() to validate the given fields. and we create showErrorMsg() and hideErrorMsg(obj) to show and hide error. function showErrorMsg(obj) { obj.addClass('border-red'); obj.after('<span class="error error-massage">Required</span>'); } function hideErrorMsg(obj) { obj.find('.border-red').removeClass('border-red'); obj.find('span.error').remove(); } function validateEmail($email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; return emailReg.test( $email ); } function checkQuoteFrm() { hideErrorMsg($('#quoteForm')); var error = false; if ($('#quoteForm input[name="name"]').val() == '') { showErrorMsg($('#quoteForm input[name="name"]')); error = true; } if( !validateEmail('#quoteForm input[name="email"]')) { showErrorMsg($('#quoteForm input[name="email"]')); error = true; } $('#quoteForm').find('.border-red').each(function(index, el) { $(this).change(function(event) { checkQuoteFrm(); }); }); return !error; } $("#quoteSubmit").click(function(event) { if(checkQuoteFrm()){ /* Your Code Here */ } });

Step 4: Add Css Class

Add two classes border-red and error in your style. .border-red{border:1px solid red;} .error{color:red;}