2017-04-10 98 views
0

我需要更改jQuery驗證Plugin的默認錯誤消息。我已經學會了如何從here實現這個目標,並且這個工作很棒。不過,我需要更多的習慣。是否可以根據輸入字段的類型設置不同的錯誤消息。 我的意思是:jQuery驗證,基於輸入類型的不同錯誤消息

<input type="text" required> 

默認錯誤massege應該是「填補這一領域的需要。」併爲

<input type="file" required> 

默認錯誤集團應該是「附加文件是必需的」。 我知道我能爲這樣的領域分別設置錯誤信息:

$('form').validate({     
    messages: { 
     FieldName: { required: "Attaching document is required" } 
    } 
}); 

問題是,形式確實非常大,所以我想單獨寫錯誤信息不會是很好的解決方案。

+0

如果你不介意,你可以說你的表格中有多少個文本框/文件字段? –

+0

有9種不同尺寸的表格,總共有近300個輸入字段,其中48個是「文件」字段@SarojSasmal –

回答

-1

給每個輸入字段一個不同的名稱和單獨創建的驗證規則名稱

假設你有2個字段:

<input type="text" name="textfield" required> 
<input type="file" name="filefield" required> 

那麼你的驗證消息將是:

var validator = $("form").validate({ 
rules: { 
    textfield: "required", 
    filefield: "required", 
}, 
messages: { 
    textfield: "Filling this field is required", 
    textfield: "Attaching document is required", 
} 
} 
+0

謝謝您的回答,但請再次閱讀問題。我已經解釋了爲什麼給定的解決方案不可接受 –

+0

我對您的情況有1種解決方法。你不必爲每個字段聲明消息,但是我想你已經爲所有字段設置了'name'屬性。然後遍歷所有字段,檢查字段類型併爲validator.messages的值構建一個對象。類似這樣的:'if(field.attr(「type」)=='text'){msgObj [field.attr(「name」)] =「填寫這個字段是必需的}},之後是:驗證器。 messages = msgObj;' –

+0

*「我有1解決方法」*〜不需要;已經有一個內置的方法。另外,當在輸入中使用'required'屬性時,將聲明放入'rules'對象內是完全多餘和多餘的。 – Sparky