parsley.js catching all errors and outputting via a javascript alert()

半腔热情 提交于 2019-12-12 10:22:42

问题


I want to catch all errors on a form using pasley v2.8 in a single event and then display those errors via a standard javascript alert.

I had this working in part before thanks to assistance in this SO question about the fieldinstance functionality. However the code in that other question works with a function being called as every form element fails.

What I want is an event that fires just once after all the errors have been collated. I believe this is done via the recent form:error event. The code I've made isn't working due to getErrorsMessages() seeming to not function. What I have so far is...

$('#form').parsley().on('form:error', function (formInstance) {
    var errorMsg = ParsleyUI.getErrorsMessages(formInstance);
    alert(errorMsg);
});

回答1:


Use the formInstance to loop through each field and retrieve the error messages. Like this

<form class="demo-form">
    <input type="text" name="field1" required />
    <input type="text" name="field2" required />
    <input type="submit" />
</form>

<script>
$(function () {
    $('.demo-form').parsley().on('form:error', function (formInstance) {
        var errors = [];

        // You have access to each field instance with `formInstance.fields`
        for (var idx in formInstance.fields) {
            errors.push((formInstance.fields[idx].getErrorsMessages()));

            // Use $element to access the jQuery element of each field
            console.log(formInstance.fields[idx].$element);
        }

        alert(errors);
    });
});
</script>

If you want to remove the messages next to each field that are displayed automatically by Parsley, you can add the following attribute to your form: data-parsley-errors-messages-disabled. See this answer.



来源:https://stackoverflow.com/questions/48409242/parsley-js-catching-all-errors-and-outputting-via-a-javascript-alert

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