2011-12-03 58 views
0

验证我的表单,我已经包含了html代码片段。对于我的配置文件类型,如果在配置文件类型中选择值2,则使用显示/隐藏编码来显示另一个div。我需要在这里发生的是jquery.validate只验证div id="pro2"的表单元素,如果没有,那么不显示错误,因为它没有完成。jQuery和jquery.validate只有在显示div时验证表单元素(显示/隐藏)

问题是我该怎么做?

<script type="text/javascript"> 
$(document).ready(function() { 
    function showDiv(element, pro2) { 
     if (pro2.children("option:selected").val() == 2) element.show(); 
     else element.hide(); 
    } 
    var myElement = $("div#pro2"); 
    var mypro2 = $("select#ptype"); 
    $("select").change(function() { 
     showDiv(myElement, mypro2) 
    }); 
    $("#ctry").change(function() { 
     $(".state").hide(); 
     var stateSelect = $("#state_" + $(this).val()); 
     stateSelect.show();  
    }); 
    $("input[data-code]").each(function() { 
     $(this).autocomplete("/js/zip/" + $(this).data("code") + ".php", { 
     matchContains: true, matchFirst: true, mustMatch: false, 
     selectFirst: false, cacheLength: 10, minChars: 1, autofill: false, 
     scrollHeight: 150, width: 180, max: 20, scroll: true 
     }); 
    }); 
    $("#form1").validate({ 
     errorLabelContainer: $("#form1 div.error") 
    });  
    // $("#reg_form").validate();  
}); 
</script> 

HTML代码:

<div class="error"></div>  
<label>Profile Type:</label> 
      <select name="add[type]" id="ptype" 
      title="Select Profile Type!" class="{validate:{required:true}}"> 
      <option value="">-- Select</option> 
      <option value="2">(MF/FF/MM)</option> 
      <option value="1">F or M</option> 
      </select> 


    <div id="pro1">   
      <label>First Name:</label> 
      <input type="text" name="add[name]" size="20" maxlength="15" id="fname" 
      title="Your First Name" class="{required:true,minlength:1}"/> 
      <span class="rsmall">internal use not displayed</span><br /> 
    </div> 
    <div id="pro2"> 
      <label>First Name:</label> 
      <input type="text" name="cpl[name]" size="20" maxlength="15" id="fname" 
      title="Your First Name" class="{required:true,minlength:1}"/> 
      <span class="rsmall">internal use not displayed</span><br /> 
    </div> 

回答

1

其实这应该工作。 jquery.validate在默认情况下忽略所有隐藏的字段(如果你想自定义这种行为,它有一个选项“ignore”,默认设置为“:hidden”)。

Ther在你的代码中有两件奇怪的事情,你的输入字段使用相同的id“fname”,而不是class="{required:true,minlength:1}"它应该是class="required" minlength="1"。至少在jquery.validate plugin I am using。也许你正在使用不同的插件或旧版本?

+0

谢谢,我不知道它会忽略隐藏的字段。我在第一个演示中也使用了相同的jquery.validate http://jquery.bassistance.de/validate/demo/errorcontainer-demo.html'class =“{required:true,minlength:1}”' – acctman