2014-09-03 80 views
4

我用MVC 4设计的表单具有多个DIVS,每个元素都有很多元素。我的目标是在用户完成字段时打开/关闭DIVS。但是,我想对每个DIV使用不显眼的验证,而不是整个表单。这可能没有单独检查每个元素?也许使用DIV ID或什么?我不想构建这个庞大的函数来检查每个DIV中的每个元素,只有这样用户才能移动到下一个DIV。MVC强制元素组jQuery验证

我想这一点,它不工作:

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

当你验证一个div内的元素?例如,当div中的最后一个元素失去焦点或者当你点击一个按钮来显示下一个div时? – 2014-09-03 12:25:37

+1

在这种情况下,当用户单击Next时,它会调用一个函数来隐藏第一个div并显示第二个div。但是我想在显示第二个div之前检查第一个div中的元素?那有意义吗? – 2014-09-03 12:27:33

回答

6

可以使用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'); 
    } 
}); 
+0

检查我的编辑并让我知道为什么不起作用 – 2014-09-03 13:36:30

+0

没有理由将它放入数组中。在'var controls = ...'后面,然后'$ .each(controls,function(index,item){$(“#form1”)。validate()。element($(this));' - 或者它可能需要成为'..element($(this)[0]);' - 不知道没有测试 – 2014-09-03 13:37:32

+0

您能否为我写出函数? – 2014-09-03 14:03:29