我的表单中有许多不同的部分,每个部分的输入必须等于要验证的表单的第一个输入(在其自己的部分中)。
验证工作正常,唯一的问题是,当用户尝试验证某个部分包含不正确的数字时,UI 会在该部分的其余部分显示错误。在这种情况下,该部分中的每个输入都会显示错误。这很棒。但是,当用户更改其中一个字段中的数字并且总数现在正确时,欧芹只会清除该特定字段中的错误。
这里的代码工作正常,但没有清除错误:
window.ParsleyValidator
.addValidator('sumTotal', function (value, group) {
// get total enrollment number
var totalInput = $('#enrollment-group').find('[data-parsley-sum-total="all"]')
var totalEnrollment = parseInt(totalInput.val())
// sum up input values for the section
var sectionSum = 0;
$('#enrollment-group').find('[data-parsley-sum-total="' + group + '"]').each(function(){
if ($(this).val()) sectionSum += parseInt($(this).val());
})
// if no inputs, don't consider the section
if (sectionSum === 0) return true
return totalEnrollment === sectionSum;
}, 32)
.addMessage('en', 'sumTotal', 'The total sum for all %s fields must equal the total enrollment above: ' + $('#enrollment-group').find('[data-parsley-sum-total="all"]').val());
// exclude the 'total enrollment' input from the sum validation
$('form').parsley({ excluded: '[data-parsley-sum-total="all"]' });
这是我尝试清除错误的代码示例,但最终导致无限递归:
$('form').parsley().subscribe('parsley:field:success', function(input){
$.each($('[data-parsley-sum-total]'), function(i, value){
if ($(value).hasClass('parsley-error')){
$(value).parsley().validate()
}
})
});
那么,一旦该部分有效,如何清除该部分中输入的所有错误?
这是在 django 管理模板中,因此我必须在加载 parsley.js 后添加自定义验证器。预先感谢您的帮助。
最佳答案
好吧,经过一番摆弄后,我发现了这一点,这适用于遇到类似问题的任何人:
window.ParsleyValidator
.addValidator('sumTotal', function (value, group) {
// get total enrollment number
var totalInput = $('#enrollment-group').find('[data-parsley-sum-total="all"]')
var totalEnrollment = parseInt(totalInput.val())
// sum up input values for the section
var sectionSum = 0;
$('#enrollment-group').find('[data-parsley-sum-total="' + group + '"]').each(function(){
if ($(this).val()) sectionSum += parseInt($(this).val());
})
// if no inputs, don't consider the section
if (sectionSum === 0) return true
return totalEnrollment === sectionSum;
}, 32)
.addMessage('en', 'sumTotal', 'The total sum for all %s fields must equal the total enrollment above: ' + $('#enrollment-group').find('[data-parsley-sum-total="all"]').val());
// exclude the 'total enrollment' input from the sum validation
$('form').parsley({ excluded: '[data-parsley-sum-total="all"]' });
// clear other errors in section if one field emits success event
$('form').parsley().subscribe('parsley:field:success', function(input){
$.each($('[data-parsley-sum-total]'), function(i, value){
if ($(value).attr('data-parsley-sum-total') == input.options.sumTotal){
window.ParsleyUI.removeError($(value).parsley(), 'sumTotal')
$(value).removeClass('parsley-error')
$(value).addClass('parsley-success')
}
})
})
关于javascript - 当单个字段在没有无限递归的情况下发出成功事件时,我无法在欧芹中触发验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29653592/