问题
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