Client side form validation using jQuery

Hello folks!

I am very excited for this blog tutorial on how to implement a dynamic form validation by using jQuery. We will see what are the most crucial validation rules that must be applied to any typical form inputs. We will use jQuery of course, because it’s super simple and quick. During my early stage of becoming a web developer, I always loved to play with jQuery because it’s very simple to understand and easy to use, however later on I started using vanilla JavaScript for HTML5 based game projects. Click below link to check it out!

Charotar IT Solutions – Portfolio

So what is jQuery?

jQuery is a fast, small, and feature-rich JavaScript library “

It has very simple and straight forward syntax. To execute or do something once the web page DOM is loaded completely, in jQuery we have to just write following lines.

$(document).ready(function(){
// code here…
}

Now let’s see how to select any DOM element in jQuery.

Suppose, there is a button tag in our HTML document which we need to capture and then attach an event on it.

<button id="submit">Save</button>

Above is a HTML code for a button and it has id “submit” – now let’s see how it’s captured and attached by a Click event using jQuery.

$(“#submit”).on(“click”, function() {
// code here…
});

Now let’s use it for validating our HTML form. There are mainly five to six types of form inputs like text, password, number, email, radio, checkbox, textarea, range, and select.

Given below are the most useful and crucial validation rules that we should use in our daily web programming life.

  • Empty input field
  • Length of input data
  • Match two input data (password & repeat-password)
  • Strength check for password
  • Format for email address
  • Malicious script / HTML special chars filter

So now let’s see one by one with the examples

Validation for “Empty Field”

HTML Code:

<form onsubmit="return false;">
<input type="text" id="username">
<button type="submit" id="submit">
</form>

In above html code there is one input text with id username and one button to submit a form having its id submit

jQuery Code:

$(document).ready(function(){
    $("#submit").on("click", function(){
        var username = $("#username").val();
        if(username.length <= 0 || username == "" || username == null) {
            alert('Please Enter Username!');
            $("#username").focus();
            return false;
        }
    });
});

Quick explanation:

When user will hit the submit button we are checking three things using IF condition. First is the length of a input data, second is ” “ (empty quotes) and third is null. Hence we can precisely prevent form to be submitted if the input data string is empty.

Validation for “min-max Input Length”

Sometimes, we need to set a limit to the user’s input data. For example: A user must enter a password between the length of 5 to 12 characters only.

HTML code:

<input type="password" id="password">

jQuery code:

var password = $("#password").val();
if(password.length < 5 || password.length > 12) {
    alert('Password must be between 5-12 characters long!');
    $("#password").focus();
    return false;
}

Validation for “matching two values”

HTML code:

<input type="password" id="password">
<input type="text" id="rePassword">

jQuery code:

var password = $("#password").val();
var rePassword = $("#rePassword").val();

if(password !== rePassword){
    alert('Password mismatched! Please enter again');
    $("#rePassword").focus();
    return false;
}

Validation for “password’s strength”

Here we will code a jQuery script to detect the weak passwords and it will be done by checking for special characters, length, UPPER & lower case etc.

jQuery code:

var password = $("#password").val();
var strength = 0;
//checking for lower case a-z
if (password.match(/[a-z]+/)) {
	strength += 1;
}
//checking for UPPER CASE A-Z
if (password.match(/[A-Z]+/)) {
	strength += 1;
}
//checking for digits [0 to 9]
if (password.match(/[0-9]+/)) {
	strength += 1;
}
//checking for special characters
if (password.match(/[$@#&!]+/)) {
	strength += 1;
}
if (strength !== 4) {
    alert('Your password is weak!);
    return false;
}

Validation for “E-mail address”

Now let’s see how we can check if an entered email has valid address format or not by using REGEX (Regular Expression)

let regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var email = $("#email").val();
if(!email.match(regex)) {
    alert('Invalid Email address!');
    return false;
}

Sanitize input data

This is important, client side & server side as well to prevent such attacks like SQL Injection, XSS etc.

function sanitizeData(string) {
  const reg = /[&<>"'/]/ig;
  const esc_map = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      '"': '&quot;',
      "'": '&#x27;',
      "/": '&#x2F;',
  };
  return string.replace(reg, (match)=>(esc_map[match]));
}
var comment = sanitizeData($("#comment").val());

Above given sanitizeData function will sanitize not only HTML entities but HTML attributes also.

That’s all for now! If you get any value or help from this quick tutorial please share it, comment below your feedback and suggestions as well. And I promise I will keep improving to make it easy to read & understand for everyone.

Thanks for visiting and reading.

Have a great day 🙂

Leave a comment

Your email address will not be published. Required fields are marked *