问题
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
*/
}
});
}
});
回答1:
If you know which field is invalid, you can use this function. http://docs.jquery.com/Plugins/Validation/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".
来源:https://stackoverflow.com/questions/6758036/how-to-manually-invalidate-fields-after-ajax-call-with-jquery-validate