我正在尝试显示所需控件的星号.代码在所需的类中运行良好但现在我有两个字段,公司和名称.根据其他元素值,只需要其中一个.是否可以在不验证控件或表格的情况下检查是否需要输入?
示例html结构:
<div class="form-group">
<label class="control-label" for="CompanyName">Company Name</label>
<div>
<input type="text" id="CompanyName" name="CompanyName" class="form-control required">
</div>
</div>
JS:
validationoptions: {
ignore: ":disabled,:hidden",rules: {
CompanyName: {
required: function () {
return ($("#ContactName").val().length === 0);
}
},ContactName: {
required: function () {
return ($("#CompanyName").val().length === 0);
}
}
},onkeyup: function (element) {
const $parent = $(element).parents(".form-group");
if ($(element).valid()) {
$parent.removeClass("invalid");
} else {
$parent.addClass("invalid");
}
},onfocusout: function () {
if ($("form").valid()) {
$("form.error").removeClass("error");
$("form .invalid").removeClass("invalid");
}
},errorPlacement: function (error,element) {
const $parent = $(element).parents(".form-group");
if ($(element).hasClass("error")) {
$parent.addClass("invalid");
} else {
$parent.removeClass("invalid");
}
},invalidHandler: function (event,validator) {
$.each(validator.successList,function (index,item) {
$(item).parents(".form-group").removeClass("invalid");
});
const errors = validator.numberOfInvalids();
if (errors) {
$.each(validator.errorList,item) {
$(item.element).parents(".form-group").addClass("invalid");
});
}
}
}
当然,我可以将我的代码放在上面所需的回调中,但这不是通用的解决方案.
我希望能够多次调用以下函数来根据所需的字段状态更新表单上的(引导程序)星号.
appendFormControlAsterisk: function ($panel) {
//removeFormControlAsterisk($panel);
let $controls = $(".form-control.required");
$controls.each(function () {
const $label = $(this).parents(".form-group").find(">.control-label");
$label.html($label.html() + " <span class='text-danger'>*</span>");
});
},
试图完成以下事情:
appendFormControlAsterisk: function ($panel) {
//removeFormControlAsterisk($panel);
let $controls = $(".form-control");
$controls.each(function () {
if ($(this).isrequired()) {
const $label = $(this).parents(".form-group").find(">.control-label");
$label.html($label.html() + " <span class='text-danger'>*</span>");
}
});
},
解决方法
Is it possible to check if an input is required without validating the control or the form?
作为jQuery Validate插件的一部分,没有方法可以返回已声明,已定义或已分配规则的列表. (你可以查看settings.rules对象里面的值,但这不是动态的或全面的)
但是,插件中内置了一个名为.check()的未记录方法,该方法将检查有效性而不会触发任何错误消息.它不仅限于所需的规则,只是有效性.它实际上只是在字段空白时查找所需的规则.
换句话说,在空白表单上,此方法将始终判断是否需要该字段而不触发消息.
您必须将它附加到验证器对象,并且参数必须是DOM元素.
$('#myform').validate().check($('[name="test3"]')[0]) // <-- returns a boolean if defined
要么
var validator = $('#myform').validate({...}); // initialize plugin with options
validator.check($('[name="test3"]')[0]) // <-- returns a boolean if defined
演示:jsfiddle.net/we2johru/2/
请注意,此方法仅在定义规则时返回布尔值.如果没有定义的规则,此方法将返回undefined.