我使用Parsley.js来验证this example中的部分表单。但是,validate()
方法始终返回false
,即使该表单应该验证。
没有显示任何错误消息,我想看看验证失败的原因。
我无法看到让Parsley简单地返回找到的所有错误的方法,所以我可以在控制台中看到它们。我错过了一些明显的东西吗?
答案 0 :(得分:8)
您可以使用以下内容:
window.Parsley.on('field:error', function() {
// This global callback will be called for any field that fails validation.
console.log('Validation failed for: ', this.$element);
});
答案 1 :(得分:2)
可能(希望)有更好的方法可以做到这一点,但这种事情是我最终用来获得一些洞察正在验证的内容以及未通过的内容:
function validateAnswers(groupName) {
var formInstance = $('.my-form').parsley();
var isValid = formInstance.validate(groupName);
// Just for debugging:
$.each(formInstance.fields, function(idx, field) {
if (typeof field.validationResult === 'boolean') {
// Validated.
console.log('Passed: ' + field.value);
} else if (field.validationResult.length > 0) {
console.log('Failed: ' + field.validationResult[0].assert.name);
}
});
return isValid;
}
这是我的非常简单的表格,带有“必需的”单选按钮;不知道它如何适用于具有不同类型的字段和验证要求的大型表单。
有更好的答案或改进吗?
答案 2 :(得分:0)
这是我为这种情况所做的。
var formElements = $('form .elementClass').parsley(); // Get all elements inside your form
// Loop through all the elements found
_.forEach(formElements, function(formElement) { //You can use a regular for loop if you prefer
var errors = ParsleyUI.getErrorsMessages(formElement); //Get the list of errors for this element
if (errors.length) {
// Output the first error in the array. You could loop this too.
console.log(errors[0]);
}
});
感觉有点难看,但它可以满足你的需要。