簡體   English   中英

jQuery驗證-在錯誤消息中顯示字段名稱

[英]JQuery validation - show field name in error messages

顯示錯誤消息時, JQuery validate插件將{number}格式用作傳遞給規則的參數的占位符。 (例如, this field must be between {0} and {1} characters

但是,我找不到使用$.validator.messages數組將字段名傳遞給全局范圍內的消息的方法。

因此,而不是靜態的:

this field is required

我想通過類似:

the {fieldname} field is required

在我的服務器端框架Laravel中, :attribute plcaheholder達到了這個目的。 插件支持此功能嗎?

您可以傳遞一個函數作為消息值,例如

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

演示: 小提琴

有很多方法可以使用JQuery Validate定制錯誤消息。 更改驗證器原型是一種方法,但還有更多方法。 使用哪種取決於您的最終目標。 例如,您想要的粒度(請參見下面的代碼段示例)。

可以在以下位置找到有關錯誤消息的特定文檔: https : //jqueryvalidation.org/reference/#link-error-messages

使用傳遞給validate()的options對象上的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  name@domain.com"
    }
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM