我使用MVC 4设计的表格有多个DIVS,每个DIVS都有很多元素。我的目标是在用户完成字段时打开/关闭DIVS。但是,我想在每个DIV上使用不显眼的验证,而不是整个表格。如果不单独检查每个元素,这可能吗?也许使用DIV ID或其他东西?我不想构建这个庞大的函数来检查每个DIV中的每个元素,这样用户就可以移动到下一个DIV。
我正在尝试这个并且它无效:
var elems = [];
var valid = true;
("#Contact").find('.text_input').each(function() {
elems.push(this.id);
}
for (var i = 0; i<= elems.length; i++) {
if ($("#" + elems[i]) != undefined) {
$("#form1").validate().element("#" + elems[i]))
if ($("#" + elems[i]).valid()) {
}
else {
valid = false;
}
}
}
但我一直收到一个未定义的错误。 DIV中具有类text_input的元素是需要验证的元素。
答案 0 :(得分:8)
您可以使用Validator.element(element)
- see documentation here验证各个控件,因此您可以使用以下方法(您尚未发布视图html,因此无法编写实际代码你)
在“下一步”按钮中单击事件
div
- 例如var controls = $(this).closest('div').find('input, textarea, select');
$.each
循环中,请致电$("form").validate().element($(this));
$(this).valid();
修改(已添加示例)
查看
<div class="section">
<h2>Section 1</h2>
.... // Your inputs and validation
@Html.LabelFor(m => m.SomeProperty)
@Html.TextBoxFor(m => m.SomeProperty)
@Html.ValidationMessageFor(m => m.SomeProperty)
<div class="error"></div>
<button type="button" class="next">Next</button>
</div>
<div class="section">
<h2>Section 2</h2>
.... // Your inputs and validation
<div class="error"></div>
<button type="button" class="next">Next</button>
</div>
<div class="section">
<h2>Section 3</h2>
.... // Your inputs and validation
<div class="error"></div>
<button type="submit" class="next">Submit</button> // submit button for last section
</div>
CSS
.section:not(:first-of-type) {
display:none;
}
脚本
$('button').click(function () {
var container = $(this).closest('.section');
var isValid = true;
$.each(container.find('input'), function () {
$('form').validate().element($(this));
if (!$(this).valid()) {
isValid = false;
return false;
}
});
if (isValid) {
container.next('.section').show().find('input').first().focus();
container.hide();
} else {
container.find('.error').text('please complete');
}
});