Saturday, September 12, 2009

Required Field Validation Using Jquery

In this post I will show you how you can validate the required fields of the form. For this post I have simple form which has first name, last name, email address , user name and the password field, and also two button controls one for save which is used to check for the required fields and the cancel button. Here is the main form of the source example.

And here is the output of the main form when user click on the save button, as you can see that First name , Email address , login name and password fields are required so the border and the back ground color of these field change to red, to indicate that these fields are required.

Here is my Code which is written on the form and which is used to attached the click event with the button control.In the click event I have called the validation() function which is written on the plug-in.
$("#cmdSave").click(function ()
return $('#'+'<%=frmMainForm.ClientID %>').validation();
And here is my plug-in code which is used to check for the required field in the form. Here in the code I have first search the control which has .reg css class in the form by using the each of the jquery.
var blnIsError = true;
$('.req', this).each(function() {
if ($(this).val()== "")
$(this)[0].title='Enter required field.';
blnIsError =false;

$('.req').bind("keyup", function()
if($(this).val() !='')

return blnIsError;
Then in the function I have check the val() of the current control and if the value of the current control is empty string then add new class of css which has property of the background color and the border of the control to be set to red. After checking for the required field by using the reg css class, then I have bind keyup event to each of the reg control so if user enter the value in the control then the Error message class will be removed from that control.

You can download the source code from here

Note: In order to work with this plug-in you have to add reg. class with the control which are required field.
All and any comments / bugs / suggestions are welcomed!

1 comment:

Anonymous said...

I know it's old but thanks!