问题
I am trying to make validation with Jquery .validate plugin.
I can't use errorPlacement and showErrors methods together.
JsFiddle: Working errorPlacement - http://jsfiddle.net/5RrGa/1861/
Working showErrors - http://jsfiddle.net/5RrGa/1862/
I need to combine them both to work together.
$("#form").validate({
ignore: [],
errorPlacement: function(error, element) {
// if showErrors exists, this block is skipped.
error.insertAfter(element);
},
showErrors: function(errorMap, errorList){
for (var i = 0; errorList[i]; i++) {
var errorElement = this.errorList[i].element['attributes']['field']['value'];
$('#allErrors').append("<p>" + errorElement + "</p>");
}
},
submitHandler: function(form) {
// Submit the form
form.submit();
},
invalidHandler: function(event, validator) {
// Show message with errors
$('#errordiv').show();
}
});
When i remove showErrors, errorPlacement works perfect. If I try to use showErrors it skips errorPlacement.
If I put showErrors before errorPlacament nothing changes, errorPlacement still don't work.
How to make both methods to work together?
回答1:
Both works with
showErrors: function(errorMap, errorList){
this.defaultShowErrors();
},
回答2:
You could do this:
$(document).ready(function(){
$("#registerForm").validate({
errorPlacement: function(error, element) {
error.insertAfter(element);
},
showErrors: function(errorMap, errorList){
var $errorDiv = $("#errordiv").empty().show();
this.defaultShowErrors();
var errorsCombined = "";
for(var el in errorMap){
errorsCombined += "<b>"+ el + "</b>" + errorMap[el]+"<br/>";
}
$errorDiv.append(errorsCombined);
},
submitHandler: function(form) {
// Submit the form
form.submit();
},
invalidHandler: function(event, validator) {
}
});
});
Fiddle: http://jsfiddle.net/maverickosama92/5RrGa/1863/
来源:https://stackoverflow.com/questions/40170848/form-validate-with-jquery-use-both-errorplacement-and-showerrors