2012-12-17 102 views
3

所以我在處理jQuery驗證插件時遇到了一些問題。我有3個選擇標籤,因此用戶可以輸入他們的生日。我如何開始爲3個選擇標籤提供1條驗證消息?我聽說也許可以做一個自定義規則?使用jQuery驗證插件驗證多個選擇框

這裏是HTML和我已經包括一個jsfiddle。

<form id="commentForm" action="" method="post"> 
<p> 
    <label for="month">Birthday:</label> 
    <select name="month" class="required select"> 
     <option value="">Month</option> 
     <option>Jan</option> 
     <option>Feb</option> 
    </select> 
    <select name="day" class="required select"> 
     <option value="">Day</option> 
     <option>01</option> 
     <option>02</option> 
    </select> 
    <select name="year" class="required select"> 
     <option value="">Year</option> 
     <option>1990</option> 
     <option>1991</option> 
    </select> 
</p> 
<input type="submit" value="Sign Up" class="button"> 
</form>​ 

This是目前正在進行的一個例子。

在此先感謝。

回答

4

您可以使用group選項將字段組合在一起,以便爲該組顯示一條錯誤消息。然後,您可以放置​​在那裏你希望使用errorPlacement選擇一個錯誤信息:

$("#commentForm").validate({ 
    groups: { 
     birthday: "month day year" 
    }, 
    errorPlacement: function(error, element) { 
     var name = element.prop("name"); 
     if (name === "month" || name === "day" || name === "year") { 
      error.insertAfter("select[name='year']"); 
     } else { 
      error.insertAfter(element); 
     } 
    } 
}); 

例子:http://jsfiddle.net/atLV4/3/

+1

+1,漂亮的答案,可以在設置像'這些字段是required'自定義消息? –

+2

@SheikhHeera:謝謝!是的,你可以填充你可以提供給'validate'的'messages'選項。不過,您必須爲組中的每個字段提供錯誤消息。 –

+0

非常感謝。它效果很好!顯然,從jsfiddle複製js有時會導致「語法錯誤:非法字符」。讓我永遠解決這個問題。只需要手工輸入整個事物。 – SeanWM