2014-10-05 77 views
1

當顯示錯誤消息時,JQuery validate插件使用{number}格式作爲參數的佔位符傳遞給規則。 (例如this field must be between {0} and {1} charactersJQuery驗證 - 在錯誤消息中顯示字段名稱

我不能然而,想出一個辦法傳遞字段名稱到消息在全球範圍內,使用$.validator.messages陣列。

因此,而不是靜態的:

this field is required

我想通過這樣的:

the {fieldname} field is required

在Laravel,我的服務器端框架,該:attribute plcaheholder發球這個目的。 該功能是否支持插件?

回答

5

您可以將一個函數作爲消息值一樣

$.validator.messages.required = function (param, input) { 
    return 'The ' + input.name + ' field is required'; 
} 

演示:Fiddle

+0

+1好答案。 – Sparky 2014-10-05 17:38:39

0

有相當多的方式與JQuery驗證來定製你的錯誤消息。更改驗證器原型是一種方法,但還有更多。使用哪一個是以您的最終目標爲準。例如,你想要的粒度如何(參見下面的示例代碼片段)。

上的錯誤消息的具體的文檔可以在這裏找到:https://jqueryvalidation.org/reference/#link-error-messages

單獨特異於每種錯誤類型的每個場的完全控制是可用的使用消息上的選項屬性對象傳遞到驗證()。這裏有一個例子複製從https://jqueryvalidation.org/validate/其中有一個電子郵件字段有兩個驗證規則:所需的和電子郵件格式...

$("#myform").validate({ 
    rules: { 
    name: "required", 
    email: { 
     required: true, 
     email: true 
    } 
    }, 
    messages: { 
    name: "Please specify your name", 
    email: { 
     required: "We need your email address to contact you", 
     email: "Your email address must be in the format of [email protected]" 
    } 
    } 
}); 
相關問題