注意:以下代码仅用于演示,我正在使用jQuery和jQuery验证插件.
假设我有一个包含两个字段(电子邮件和库存号)的表单:
<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>
绑定插件形成:
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 */ } }); } });
如果您知道哪个字段无效,您可以使用此功能.
http://docs.jquery.com/Plugins/Validation/Validator/showErrors
http://docs.jquery.com/Plugins/Validation/Validator/showErrors
var validator = $( "#myshowErrors" ).validate(); validator.showErrors({ "firstname": "I know that your firstname is Pete,Pete!" });