Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually invalidate fields after AJAX call with jQuery validate

Tags:

Note: the below code is just for demonstration and I am using jQuery and jQuery validate plugin.

Suppose I have a form with two fields (email and inventory number):

<form action="/something" method="post" id="demoForm">      Inventory No: <input type="text" class="required" name="inventory_no" />      Email: <input type="text" class="required" name="email" />      <input type='submit' value='submit' /> </form> 

Binding plugin to form:

jQuery(function(){     jQuery('#demoForm').validate(); });  //handle user submit  jQuery('#demoForm').bind('submit', function (e) {     e.preventDefault();      if (jQuery(e.target).valid()) {         //form is valid submit request thru ajax          jQuery.ajax({             /*more options here*/              success: function (data) {                  /*                  Server process request and finds that, email is already in use                  and inventory number is invalid                  so it sends data in some format may pe JSon                  with field names and message indicating errors                  eg: Email:"Already in use"                  InventoryNo: "Invalid Inventory No",                  Now can i invalidate these two fields on form mannualy                  and display the message received from server for each field                 */             }         });     } }); 
like image 429
Praveen Prasad Avatar asked Jul 20 '11 06:07

Praveen Prasad


1 Answers

If you know which field is invalid, you can use this function. Old URL http://docs.jquery.com/Plugins/Validation/Validator/showErrors New URL https://jqueryvalidation.org/Validator.showErrors/

var validator = $( "#myshowErrors" ).validate(); validator.showErrors({   "firstname": "I know that your firstname is Pete, Pete!" }); 

Where firstname is the name property of your field; ie name="firstname".

like image 155
iboware Avatar answered Sep 21 '22 19:09

iboware