2013-02-28 147 views
3

我有一個奇怪的問題。我有一個文件上傳和幾乎沒有其他textarea的表單。每個字段都是必需的。所以基本上當幾個字段留空時,驗證工作正常,但當且僅當文件上傳空白時,表單纔會被提交。使用jQuery驗證插件進行文件上傳驗證

這裏是我的代碼

<li > 
    <p> 
    <label for="rad">radio label: 
    </label><br> 

    <input type="radio" name="rad" value="yes" style="width:20px">&nbsp; Yes&nbsp;&nbsp;</input> 
    <input type="radio" name="rad" value="no" style="width:20px">&nbsp; No</input><br/> 
    <label for="cv" class="error" style="display:none">This field is required</label> 
    </p> 
    <p> 
    <input type="file" name="fupl" style="display:none;margin-top:10px" id="fup"/> 
    <label for="fupl" class="error" style="display:none;color:red">This field is required</label> 
    </p> 
    </li> 
    <br> 
    <li> 
    <label>checkbox label 
    </label><br><br> 
<input type="checkbox" name="cb" value="tick" style="width:20px">&nbsp;&nbsp; <small>checkbox field<small></input><br>           <label for="fee" class="error" style="display:none">This field is required</label> 
    </li> 
    <br><li> 
<input type="submit" class="button" value="SUBMIT" style="float:right"/> 
</li> 
<script> 
$(document).ready(function() 
{ 
$("input[type='radio']").change(function(){ 
if($(this).val()=="yes") 
{ 
$("#fup").show(); 
} 
else 
{ 
    $("#fup").hide(); 
} 
}); 
}); 

,這我的jQuery

$('#form').validate({ 
rules: {  
fupl: { 
    required: true, 
    accept:'docx|doc' 
    },  
+0

你在你的代碼顯示上面沒有'form'標籤。 – Sparky 2013-02-28 23:51:36

回答

13

您的代碼似乎工作得很好。驗證插件會忽略隱藏的字段。但是,當您通過單選按鈕顯示文件上載字段時,它將驗證並顯示錯誤消息。請參閱:http://jsfiddle.net/y5ghU/


您的代碼:

<input type="file" name="fupl" style="display:none;margin-top:10px" id="fup"/> 

文件上傳字段設置爲display:none;和插件將忽略默認情況下,所有的隱藏的字段。

使用ignore: []選項可禁用此功能。

$(document).ready(function() { 

    $('#form').validate({ 
     ignore: [], 
     rules: { 
      fupl: { 
       required: true, 
       accept: 'docx|doc' 
      } 
     } 
    }); 

}); 

DEMO:http://jsfiddle.net/ptV35/


編輯:不能確定的OP想要哪個方向走,但是當文件上傳字段是再下面的演示隱藏任何未決的錯誤信息-隱。

$("#fup").next('label.error').hide(); 

http://jsfiddle.net/y5ghU/4/

+0

謝謝你的工作..但它就像驗證後不久,文件上傳字段消失,只是錯誤消息顯示。我也需要顯示文件上傳字段。 – lakshganga 2013-03-01 08:36:27

+0

此外,即使我點擊「否」,那麼它也說該字段是必需的。 – lakshganga 2013-03-01 09:23:14

+0

@lakshganga,你可以添加'$(「#fup」)。next('label.error')。hide();'隱藏標籤。請參閱:http://jsfiddle.net/y5ghU/4/ – Sparky 2013-03-01 15:59:43