2013-03-06 53 views
0

我有一個表單,我想在客戶端進行驗證,並且我正在使用jQuery Validate進行該任務。驗證適用於其他(輸入)字段,但不適用於複選框。複選框將無法驗證

我在做什麼錯?

<form name="insert_new_lesson" id="insert_new_lesson" method="post" action="" class="lesson-form" enctype="multipart/form-data" novalidate="novalidate"> 
    <input class="{category: true}" type="checkbox" name="category[]" value="15" id="grade15"> 
    ... rest of the fields... 


$("#insert_new_lesson").validate({ 
    errorPlacement: function (error, element) { 
     error.insertBefore(element);  
    }, 
    rules: { 
     category: { 
      required: 'input[type="checkbox"]:checked', 
     }, 
     ...rest of the fields (validation works) 
+0

名稱中的括號是否是typeo? – xecaps12 2013-03-06 14:32:56

+0

根據您發佈的內容,您已設置了一條規則,只要表單中存在任何已選中的複選框,就會創建一個名稱爲「類別」(未在您的問題中顯示)的字段。這是你想要的嗎? – 2013-03-06 14:44:02

+0

不,方括號需要在那裏才能收集用戶選擇的複選框。 – dracula 2013-03-06 14:52:31

回答

1

試試這個:

$.validator.addMethod('atLeastOne', function(value, element, param) { 
    return $('input[name^="category"]').is(':checked'); 
}, 'Please select at least one checkbox'); 

$(function() { 
    $("#insert_new_lesson").validate({rules: { 
      'category[]': 'atLeastOne' 
     }, groups: { 
      checkboxes: 'category[]' 
     }, errorPlacement: function(error, elem) { 
      if (elem.attr('name').match(/category\[\]/)) { 
       $('input[name^="category"]:last').next().after(error); 
      } 
      else { 
       elem.next().after(error); 
      } 
     } 
    }); 
}); 
+0

太棒了,那真的有效,但是,錯誤信息直接放在複選框中,就像這樣:http://i.imgur.com/vTWkySS.png。你知道如何解決這個問題嗎? ? – dracula 2013-03-06 15:47:06

+0

我編輯了答案,使用elem.next(),以便消息出現在複選框的文本之後。 – codefreak 2013-03-06 15:52:06

+0

在更改代碼後,它們向右移動一點,但它們仍然變爲輸入字段:http:// i。 imgur.com/FlBYv2V.png。下面是完整的js代碼:http://pastie.org/private/anal4i57kfft6zvgucncpq如果你想看看(我實際上有兩組複選框,也許這就是問題所在)。我出局 – dracula 2013-03-06 16:02:17

0

你可以試試這個語法JSON(外單引號和雙重點):

class='{"category": true}' 
1

一個當前問題與jQuery驗證。 See this issue在官方存儲庫中。

正如評論指出一個,你就必須做到以下幾點,以能夠驗證具有相同名稱字段:

$.validator.prototype.elements = function() { 
    var validator = this; 
    // select all valid inputs inside the form (no submit or reset buttons) 
    return $(this.currentForm) 
     .find(":input") 
     .not(":submit, :reset, :image, [disabled]") 
     .not(this.settings.ignore) 
     .filter(function() { 
      !this.name && validator.settings.debug && window.console && console.error("%o has no name assigned", this); 
      return validator.objectLength($(this).rules()); 
     }); 
}; 

請注意,我已經從註釋修改了代碼在GitHub中。使用find("input")用戶dsand1234,這應該是find(":input")在第5行

+0

感謝您的回答。嘗試過,但它是一回事。在我的問題中設置「category」規則是否正確(即使名稱是category [])?順便說一句,我應該把它放在「$(」#insert_new_lesson「)之前或之後。validate({...」code? – dracula 2013-03-06 15:29:46

+0

@dracula,其餘代碼在哪裏?請編輯您的OP以顯示更多_complete_示例所以人們可以更好地幫助你 – Sparky 2013-03-06 15:46:34

0

這個工作對我來說,是一個簡單的解決方案。只需在你的規則中用引號括起「名字」即可。

rules: { 
    'category[]': { 
     required: true 
    } 
} 

我在another post here找到了這個解決方案。