Saturday, September 10, 2016

Validation using jQuery Validate


You can easily validate your forms using the library jQuery validate. Just download the latest version of jQuery validate and put it in your server. I'm using codeigniter and the path is /assets/js/jquery.validate.js. Include the file in the head tag of the page after jquery.
<head>
        <script src="<?php echo base_url('assets/js/jquery-2.1.0.min.js');?>"></script>
 <script src="<?php echo base_url('assets/js/jquery.validate.js');?>"></script>
</head>
Suppose you have a form like this, you can easily validate and submit it using ajax.
<form id="myform">
 <input type="text" name="name" placeholder="Enter name"/>
 <input type="text" name="mobile" placeholder="Enter mobile"/>
 <a href="javascript:void(0);" id="enter_data">Enter</a>
</form>
The submitHandler will take care of the ajax part if the form validates to true.
<script>
var site_url = "";
$(document).on('click','#enter_data', function(){
  if($('#myform').valid()) {
    $('#myform').submit();
  }
});
$('#myform').validate({
    rules: {
      // Specify validation rules- left side is the name attribute of form elements
        name: "required",
        mobile: "required"
      },
      // Specify validation error messages
      messages: {
        name: "Please enter name",
        mobile: "Please enter mobile"
      },
    submitHandler: function(form) {
        $.ajax({
            url: site_url+"/admin/enter",
            type: "POST",
            data: $(form).serialize(),
            success: function(res) {
                window.location.reload();
            }            
        });
    }
});
</script>
There are lots of options available for validation. You can read it here https://jqueryvalidation.org/