JQuery Form Validation Script

Programmer's are always wondering when it comes with validating long form with hundreds of controls. Most of the time programmers write code for saving and updating form values but validating is troublesome job for them and they often miss it or ignore is due to length of long form and too many controls. Checking validation manually using server side code is too troublesome. So, today I'm going to show you a simple jQuery for validating form. Since, it's a dynamic jQuery so you need not to worry about length of form and no. of controls on any form.

Step 1: Place the following style on your page or stylesheet.

span.required

{

    color:Red;

    font-size:10px;

span.number

{

    color:Red;

    font-size:10px;

}

span.date

{

    color:Red;

    font-size:10px;

}

span.emailid

{

    color:Red;

    font-size:10px;

} 

Next step, apply .required class to all the controls that are required in form, .number class to all number controls, .date class to all date fields and .emilid class to all email fields. And then add the below script

$(document).ready(function () {

        $('.required').parent().prev().prev().append('<span class="required">&nbsp;&nbsp;*</span>');

        $('#<%=btnSave.ClientID %>').click(function () {

            var isValid = true;

            $('input.required').each(function () {

                if (this.value == '') {

                    isValid = false;

                }

            });

 

            $('textarea.required').each(function () {

                if (this.value == '') {

                    isValid = false;

                }

            });

 

            $('select.required').each(function () {

                if (this.value == '0') {

                    isValid = false;

                }

            });

 

            if (!isValid) {

                alert('* Please fill required fields.');

            }

 

            $('input.number').each(function () {

                if (!$(this).isNumber()) {

                    alert('not a valid no.');

                    isValid = false;

                }

            });

 

            $('input.date').each(function () {

                if (!$(this).isDate()) {

                    alert('not a valid date.');

                    isValid = false;

                }

            });

 

            $('input.emailid').each(function () {

                if (!$(this).isEmail()) {

                    alert('not a valid email id.');

                    isValid = false;

                }

            });

            return isValid;

        });

    }); 

Lastly we have to reference the ValidationPlugin.js on our form page. This plugin contains definition of isNumber, isDate and isEmail functions. So, with this much work you will get your form loaded with validation on it. Originally posted on:

Simple jQuery Validation for long forms