Tuesday, January 24, 2012

jQuery Form Validation

Tired of validating the form using javascript. Here is the code to validate the form using jQuery.


  function submit_form()
{
var formElements = $('#form_name .required'); // Reading all elements in the form which are having class as required

var error = 0;

formElements.each(function() { // Looping all the elements which are having the class name as required...
if($(this).val() == "") {  // Checking the value of the field
                                                // Showing the border color as red if the field is empty
$(this).css('border','1px solid red');
error++;
} else {
                                                // removing the border if the field has the value....
$(this).css('border','none');
}
});
}

Use the submit_form function in onsubmit of the form.

The fields in the form which need to be validated should be given as below.

<input type="text" name="field_name" class="required" />

If we add the class required for the textbox, it validates otherwise it doesnot validate the textbox.


No comments: