0

I am using jquery.validate.min.js for validate a HTML form and It is working fine in normal HTML form for validation but If I am using AJAX for the form submit this is not validating the form and submit it without any validation; Below is my code.

This is the HTML of the FORM

<form id="add-form">
    <label for="roleName" class="control-label">Test:</label>
      <label for="roleName" class="field prepend-icon">
      <input id="roleName" type="text" name="roleName" placeholder='Role name' class="gui-input" maxlength="50">
      <label for="roleName" class="field-icon">
        <i class="fa fa-pencil"></i>
      </label>
   </label>
   <button type="submit" id="add_submit">Submit</button>
   <button type="reset" class="hideModal">Cancel</button>
</form>

This jQuery Validation I am using

$("#add-form").validate({
debug: false,
errorClass: "state-error",
validClass: "state-success",
errorElement: "em",
onkeyup: false,
onblur: true,
onclick: false,
rules : {
    roleName : {
        required : true,
        minlength : 2,
        maxlength : 50
    }
},
messages : {
    roleName : {
        required : 'Role name is required!'
    }
},
highlight : function(element, errorClass, validClass) {
    $(element).closest('.field').addClass(errorClass).removeClass(validClass);
},
unhighlight : function(element, errorClass, validClass) {
    $(element).closest('.field').removeClass(errorClass).addClass(validClass);
},
errorPlacement : function(error, element) {
    if (element.is(":radio") || element.is(":checkbox")) {
        element.closest('.option-group').after(error);
    } else {
        error.insertAfter(element.parent());
    }
}
}); 

By this code I am making the AJAX Call

$("#add-form").submit(function(e) {
var roleName = $('#roleName').val();
$.ajax({
    type : "POST",
    url : "userroleadd.jsp",
    timeout : 60000,
    dataType : "json",
    async : false,
    data : {
        roleName : roleName
    },
    beforeSend : function() {
        $(".spinner").show();
    },
    success : function(data) {
        alert("success");       
    },
    complete : function() {
        $(".spinner").hide();
    },
    error : function(jqXHR, exception) {
        var msg = jQuery.parseJSON($.trim(jqXHR.responseText));
    }
});
e.preventDefault();
});
Sparky
  • 98,165
  • 25
  • 199
  • 285
Zeeshan
  • 221
  • 1
  • 3
  • 7
  • you need the tag *submithandler* where you can call the ajax. Here is an example: https://stackoverflow.com/questions/11469616/jquery-form-validation-before-ajax-submit – AlbertoCh Jun 06 '18 at 15:31
  • Thanks @AlbertoCh for your help – Zeeshan Jun 07 '18 at 08:06

0 Answers0