Simple Form Validation using jQuery

In this tutorial I will cover a lightweight form validation from scratch. It is not advanced and powerful as the official plug-in. But you will get an idea on how simple it is to use jQuery to validate a form.

Prerequisites: You should be familiar with XHTML, CSS and little bit of JavaScript and jQuery before reading further. I would recommend you to go through this tutorial on jQuery to have a better understanding on few basics.

XHTML form

The mark-up is simple. I’ve not added any complex properties for any tags. I’ve tried to use the form elements that are mostly used on web.

	<form method="post" action="#nosend.php" id="basicFormVal">

		<label for="Name">Name:</label>
		<input type="text" id="name" name="name"/>

		<label for="Name">Gender:</label>
		<p><input type="radio" id="male" name="gender" /><span>Male</span></p>
		<p><input type="radio" id="female" name="gender" /><span>Female</span></p>
		<div class="clear"> </div>

		<label for="Phone">Phone:</label>
		<input type="text" id="phone" name="phone"/>

		<label for="E-Mail">E-Mail:</label>
		<input type="text" id="email" name="email"/>

		<label for="Country">Country:</label>
		<select id="country">
			<option selected="selected">Please Select your Country</option>
			<option value="DZ">Algeria</option>
			<option value="ZW">Zimbabwe</option>
		</select>

		<label for="Feedback">Feedback:</label>
		<textarea id="feedback" rows="6" cols="40"></textarea>
		<div class="clear"> </div>

		<p class="s"><input type="checkbox" id="signup" name="newsletters" />
		<label for="newsletters">Sign-up for our Newsletters:</label>
		</p>
		<div class="clear"> </div>

		<p class="formButtons">
			<input type="submit" value="Submit" id="submitBtn" />
			<input type="reset" value="Reset" id="resetBtn" />
		</p>

	</form>

jQuery

Here is the bit of jQuery I’ve used to do a simple validation on the above form.

	$(function(){
		$('#basicFormVal').submit(function() {

			if ($('#name').val() == "" || $('#phone').val() == "" ||
				$('#email').val() == "" || $('#feedback').val() == "" ||
				$("#country").prop("selectedIndex") == 0 || $("#signup").prop("checked") == false || $("input[name*='gender']").prop("checked") == false)
				{
					alert('All the fields needs to be filled');
					var flagit = false;
				}
				else { var flagit = true;}

			return flagit;
		});
	});

Let’s have a look at how the code is transformed form JavaScript to jQuery. If I have to read the form in the XHTML using JavaScript I would use the following code:

var myForm = document.getElementById("basicFormVal");

Here is how it is written in jQuery:

$('#basicFormVal')

The $ is the shortcut to access jQuery. We can select any element using the tag name or id or class like we do in css. jQuery provides all the existing JavaScript properties, functionalities and also includes some additional useful features.

Let’s see some examples.

I have a div with an ID <div id=”myDiv”>Content</div>. Below is how I can use jQuery to select or read this div.

$('#myDiv')

I have a div with class <div class=”myDiv”>Content</div>. Below is how I can use jQuery to select / read this div.

$('.myDiv')

I simple have a div <div>Content</div>

$('div')

I’ve used similar selectors like above examples but here is a selector that might look a bit complex which is not. Let’s have a look:

$("input[name*='gender']")

If you see the XHTML form I’ve used a radio button group with name=”gender”. To access this radio button group I’ve used the above selector. The above code selects elements that have the specified attribute(name) with a value(gender). It might look confusing but it is very simple. Please go through the jQuery selectors to learn more about selectors and how to use them. They are very similar to the css selectors.

Let’s move on to the methods that I’ve used in this tutorial val() and prop(). These are general methods in jQuery that can be used to retrieve the values and properties of that element.

Here is a an example:
I have an input tag <input type=”text” id=”name” name=”name”/> and I want to alert the text entered into this field.

In JavaScript:
var myInp = document.getElementById("name");
alert(myInp.value);

In jQuery:
alert($('#name').val());

The val() method in jQuery is more powerful and can do lot more than just retrieving the values of the elements. Read all about it here: val()

Now the prop() method provides a way to explicitly retrieve property values like selectedIndex, tagName, nodeType, ownerDocument, defaultChecked, and defaultSelected. You can read more about it here: prop()

Please see the below code snippets to understand the two methods better:

To check the selected item index in the country list(As in XHTML form) I’ve the below:
$("#country").prop("selectedIndex") == 0

The below code is to verify if the check box is checked:
$("#signup").prop("checked") == false

Finally the submit() method is used to trigger the validation it’s similar to the method we have in JavaScript. Read more about it here:submit().

It is always good to learn basics even though we have plug-ins for everytihng 🙂

Click here to download the complete code.

Good Luck!