How to manually invalidate fields after AJAX call with jQuery validate

六眼飞鱼酱① 提交于 2019-12-21 03:21:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!