2014-08-30 29 views
0

我有一個像這樣的表格,允許用戶上傳圖片。用戶上傳的每張圖片都顯示在名爲imgHolderdiv之外,該表格位於表格之外,並且上傳表格中的file[]輸入被刪除(用戶只能上傳5個文件)。jQuery Validation插件檢查至少已上傳一張圖片

問題我堅持是,我該如何使用jquery驗證插件來檢查imgHolderdiv以查看是否至少有一個圖像被上傳?我不需要自己檢查文件字段。我以另一種方式做。

<div class="imgHolder"> 
    <div><img src="demo-1.jpg"><i class="icon-remove"></i></div> 
</div> 

<form action="/us/imgpcr.php" method="post" enctype="multipart/form-data"> 
<div><input type="file" name="file[]"></div> 
<div><input type="file" name="file[]"></div> 
<div><input type="file" name="file[]"></div> 
<div><input type="file" name="file[]"></div> 
<input type="submit"> 
</form> 

我使用的插件很簡單的方式。

$("#images").validate({ 
    rules: { 
     albumTitle: { 
      required: true, 
      minlength: 10, 
      maxlength: 25 
     }, 
messages: { 
     itemTitle: { 
      required: "Please enter a valid title", 
      minlength: "Minimum title length required is 10 characters", 
      maxlength: "Maximum title length allowed is 25 characters" 
     }, 

但是有沒有辦法讓插件檢查窗體外面的div?

+0

在任何情況下,你絕對不能驗證'div'。你也不能驗證任何不包含在你附加到'.validate()'的'form'中的輸入元素。 – Sparky 2014-08-30 15:53:53

+0

另外,有了這個插件,你不能檢查一個文件是否已經上傳,你只能使'type =「file」'爲必填字段。 – Sparky 2014-08-30 16:10:20

回答

0

根據您發佈的代碼(或缺少代碼),jQuery Validate插件根本無法工作。

1)不能有多個具有相同name屬性的元素。 name必須是唯一的,因爲這是插件設計用於跟蹤輸入。這樣的事情會工作...

<input type="file" name="file[1]"> 
<input type="file" name="file[2]"> 
<input type="file" name="file[3]"> 
<input type="file" name="file[4]"> 

2)如果您希望這四個輸入元件中的至少一個是強制性的,你可以使用require_from_group方法,它正是這麼做的。但是,由於所有四個輸入元素都相同,因此只需製作第一個輸入元素required即可。

$("#images").validate({ 
    rules: { 
     "file[1]": { // <- must use quotes on the name because of the brackets 
      required: true 
     }, 
     albumTitle: { 
      required: true, 
      minlength: 10, 
      maxlength: 25 
     } 
    }, .... 

3)你要麼有意地messagesrules孩子或你忘記一些結束括號。該messages選項是兄弟的rules選擇,而不是孩子的 ...

rules: { 
    albumTitle: { // <- matches the 'name' attribute of the input 
     .... 
    } 
}, // <- this brace was missing 
messages: { 
    itemTitle: { // <- shouldn't this be the same 'name' used within 'rules'? 
     .... 
    } 
}, // <- this brace was missing 

4)我沒有看到你的HTML標記中命名albumTitleitemTitle任何元素,你張貼。您無法驗證form容器中不存在的任何輸入元素。

5)要連接到.validate() ... #images

$("#images").validate({... 

但是,在您的標記稱爲images沒有id。選擇器需要匹配您的form ...

<form id="images" action="/us/imgpcr.php" method="post" .... 

報價OP:

「?但是,有沒有辦法讓插件來檢查一個div那是出方的形式」

你絕對無法驗證在任何情況下一個div。您也無法驗證您已附加到.validate()form中未包含的任何輸入元素。

該插件可以只驗證<form></form>容器內<input><textarea><select>元件。沒有解決方法。

我不明白這個請求的需要。由於您要確保文件已上傳,因此只需輸入input type="file"字段。

否則,這個插件無法判斷一個文件是否已經上傳,它只能使type="file"字段成爲強制性的。