亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

jQuery Validate-至少需要填充一組字段

jQuery Validate-至少需要填充一組字段

慕虎7371278 2019-10-06 14:11:39
我正在使用出色的jQuery Validate插件來驗證某些表單。在一個表單上,我需要確保用戶填寫一組字段中的至少一個。我認為我有一個很好的解決方案,并希望與大家分享。 請提出您可以想到的任何改進。我沒有找到任何內置方法來執行此操作,因此搜索并找到了Rebecca Murphey的自定義驗證方法,該方法非常有幫助。我通過三種方式對此進行了改進:讓您傳遞一組字段的選擇器為了讓您指定必須填充多少組才能通過驗證一旦其中一個輸入通過驗證,就將該組中的所有輸入顯示為通過驗證。(請參閱對尼克·克雷弗大喊大叫。)因此,您可以說“必須至少填充與選擇器Y匹配的X個輸入”。最終結果,像這樣的標記:<input class="productinfo" name="partnumber"><input class="productinfo" name="description">...是這樣的一組規則:// Both these inputs input will validate if // at least 1 input with class 'productinfo' is filledpartnumber: {   require_from_group: [1,".productinfo"]  }description: {   require_from_group: [1,".productinfo"]}項#3假設您.checked在成功驗證后將一類錯誤消息添加到錯誤消息中。您可以按照以下說明進行操作,如此處所示。success: function(label) {          label.html(" ").addClass("checked"); }如同上面鏈接的演示中一樣,我使用CSS為每個span.errorX圖像提供背景,除非它具有class .checked,在這種情況下,它會得到一個選中標記圖像。

3 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

這是Nathan的出色解決方案。非常感謝。


這是一種使上面的代碼起作用的方法,以防有人像我那樣在集成時遇到麻煩:


Additional-methods.js文件中的代碼:


jQuery.validator.addMethod("require_from_group", function(value, element, options) {

...// Nathan's code without any changes

}, jQuery.format("Please fill out at least {0} of these fields."));


// "filone" is the class we will use for the input elements at this example

jQuery.validator.addClassRules("fillone", {

    require_from_group: [1,".fillone"]

});

html文件中的代碼:


<input id="field1" class="fillone" type="text" value="" name="field1" />

<input id="field2" class="fillone" type="text" value="" name="field2" />

<input id="field3" class="fillone" type="text" value="" name="field3" />

<input id="field4" class="fillone" type="text" value="" name="field4" />

不要忘了包含Additional-methods.js文件!


查看完整回答
反對 回復 2019-10-06
?
飲歌長嘯

TA貢獻1951條經驗 獲得超3個贊

不錯的解決方案。但是,我遇到了其他必需規則不起作用的問題。對表單執行.valid()對我來說解決了這個問題。


if(!$(element).data('being_validated')) {

  var fields = $(selector, element.form);

  fields.data('being_validated', true); 

  $(element.form).valid();

  fields.data('being_validated', false);

}


查看完整回答
反對 回復 2019-10-06
?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

謝謝肖恩。這解決了我的代碼忽略其他規則的問題。


我還做了一些更改,以使“請至少填寫一個字段..”消息顯示在單獨的div中,而不是在每個字段之后顯示。


放入表單驗證腳本


showErrors: function(errorMap, errorList){

            $("#form_error").html("Please fill out at least 1 field before submitting.");

            this.defaultShowErrors();

        },

將此添加到頁面中的某處


<div class="error" id="form_error"></div>

添加到require_from_group方法addMethod函數


 if(validOrNot){

    $("#form_error").hide();

}else{

    $("#form_error").show();

}

......

}, jQuery.format(" &nbsp;(!)"));


查看完整回答
反對 回復 2019-10-06
  • 3 回答
  • 0 關注
  • 751 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號