我创建了一个表单,每个记录都有多个输入,我可以根据需要隐藏/显示它们。
问题是当它们可编辑时,我想验证没有表单提交的值。
<form action="Update" method="post" id="frmUpdateGroup" class="frmUpdateGroup">
<div>
<input id="Name_1" name="Name_1" required class="grp-Name form-control form-control-flat" value="zzzzz" />
</div>
<div style="display:none">
<input id="Name_2" name="Name_2" required class="grp-Name form-control form-control-flat" value="" />
</div>
var $updateGroupNameValidator;
$('.frmUpdateGroup').validate({});
$updateGroupNameValidator = $('.grp-Name').validate({
rules: {
minlength: 3,
maxlength: 50,
required: true
},
messages: {
required: "group name can not be null or empty",
minlength: "group name must be at least 3 characters long",
maxlength: "group name can not exceed 50 characters"
},
highlight: function(element) {
$(element).closest('.form-group').addclass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeclass('has-error');
},
errorelement: 'span',
errorclass: 'help-block',
errorplacement: function(error, element) {
debugger;
if (element.parent('.input-group').length) {
error.insertafter(element.parent());
} else {
error.insertafter(element);
}
}
});
$('.grp-Name').blur(function(e) {
$updateGroupNameValidator.valid();
});
$('.grp-Name').keyup(function(e) {
$updateGroupNameValidator.valid();
});
我创建了JFiddle link形式,并希望在第一个文本框被清除或输入文本少于3个字符时看到错误,但是没有发生任何事情。
答案 0 :(得分:0)
我不是验证器插件的大师,但我认为你不能像你一样在单个元素上定义验证器,只为表单验证处理程序中的每个元素定义规则,如下例所示:
var validator = $("#frmUpdateGroup").validate({
// Specify the validation rules
rules: {
Name_1: {
required: true,
minlength: 3,
maxlength: 50
},
},
// Specify the validation error messages
messages: {
Name_1: {
required: "group name can not be null or empty",
minlength: "group name must be at least 3 characters long",
maxlength: "group name can not exceed 50 characters"
},
},
});
$('.grp-Name').keyup(function(e) {
$('#Name_1').valid();
// or $("#frmUpdateGroup").data('validator').element('#Name_1').valid();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<form action="Update" method="post" id="frmUpdateGroup" class="frmUpdateGroup">
<div>
<input id="Name_1" name="Name_1" required class="grp-Name form-control form-control-flat" value="zzzzz" />
</div>
<div style="display:none">
<input id="Name_2" name="Name_2" required class="grp-Name form-control form-control-flat" value="" />
</div>
</form>
&#13;