Tuesday, July 23, 2013

jQuery validation on a button click

jQuery Validation plugin , is no  doubt the first jquery plugins that is used by hundreds of users. Easy to use, pretty handy  and great user experience. For the users, what can be more better than having to know right away if they're doing it correctly.  There are  other blog where you can learn how to use the plugin correctly like one in here.

Well,  most of the site explains about the integration process with great tutorial, however this one  is just to help those who wants to  implement the validation with simple button (not submit).

Simple validation example using input type button's click event.

HTML:
Field 1:
JQUERY:
$(function() {
    $('#btn').click(function() {
        $("#form1").valid(); //validate form 1
    });
});
Validation example using jQuery UI dialog box.
HTML:


JQUERY:
$(function() {
    $('#dialogbtn').click(function() {
        $( "#dialog-form" ).dialog( "open" );
      });
    
    //code for dialog
    $( "#dialog-form" ).dialog({
      autoOpen: false,
      height: 300,
      width: 350,
      modal: true,
      buttons: {
        "Save": function() { //on click of save button of dialog
            if($('#form2').valid()){  //call valid for form2 and show the errors
               alert('submit form');  //only if the form is valid submit the form
                $( this ).dialog( "close" );
            }
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
      
    });
});