【问题标题】:MVC Force jQuery validation on group of elementsMVC 强制对一组元素进行 jQuery 验证
【发布时间】:2014-09-03 11:42:10
【问题描述】:

我用 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 类的元素是需要验证的元素。

【问题讨论】:

  • 什么时候验证 div 中的元素?例如,当 div 中的最后一个元素失去焦点或单击按钮显示下一个 div 时?
  • 在这种情况下,当用户单击下一步时,它会调用一个函数来隐藏第一个 div 并显示第二个。但是我想在显示第二个 div 之前检查第一个 div 中的元素?这有意义吗?

标签: jquery-ui asp.net-mvc-4


【解决方案1】:

您可以使用Validator.element(element) - see documentation here 验证单个控件,因此您可以使用以下方法(您尚未发布视图 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>

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');
  }
});

【讨论】:

  • 检查我的编辑并告诉我为什么这不起作用
  • 没有理由将其放入数组中。在var controls = ... 之后然后是$.each(controls, function(index, item) { $("#form1").validate().element($(this)); - 或者它可能需要是..element($(this)[0]); - 如果没有测试就不确定
  • 你能帮我写出这个函数吗?
  • 来晚了——我明天去看看
  • @StephenMuecke,很好的解决方案。很简单,代码也不多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多