MVC强制jQuery验证元素组

Dea*_*Pue 4 jquery-ui asp.net-mvc-4

我用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;
           }
        }
   }
Run Code Online (Sandbox Code Playgroud)

但我一直得到一个未定义的错误.DIV中具有类text_input的元素是需要验证的元素.

小智 8

您可以使用以下方法验证单个控件Validator.element(element)- 请参阅此处的文档,以便您可以使用以下方法(您尚未发布视图html,因此无法为您编写实际代码)

在"下一步"按钮单击事件中

  1. 选择相关内的所有控件div- 例如 var controls = $(this).closest('div').find('input, textarea, select');
  2. 在一个$.each循环中,调用$("form").validate().element($(this));
  3. 如有必要,测试是否有效 $(this).valid();
  4. 如果一切都有效,隐藏当前div并显示下一个

编辑(已添加示例)

视图

<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>
Run Code Online (Sandbox Code Playgroud)

CSS

.section:not(:first-of-type) {
    display:none;
}
Run Code Online (Sandbox Code Playgroud)

脚本

$('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');
  }
});
Run Code Online (Sandbox Code Playgroud)