語言

IValidationAttributeFormatter 介面

定義

格式化驗證錯誤訊息範本,並使用屬性特定的參數。 驗證本地化管線用於從包含位置佔位符的本地化範本產生完整格式化的錯誤訊息,這些範本包含(顯示名稱)之外 {0} 的位置性佔位符。

public interface class IValidationAttributeFormatter
public interface IValidationAttributeFormatter
type IValidationAttributeFormatter = interface
Public Interface IValidationAttributeFormatter

備註

要新增自訂驗證屬性的格式支援,有兩個選項:

  1. 直接在屬性本身實作 IValidationAttributeFormatter 。 ValidationAttributeFormatterRegistry 先檢查這個,然後自動將該屬性當作自己的格式化器使用。
  2. 建立一個獨立 IValidationAttributeFormatter 的實作,並透過 AttributeFormatters 呼叫 AddFormatter<TAttribute>(Func<TAttribute,IValidationAttributeFormatter>)註冊。
以下範例說明如何註冊自訂屬性的格式化器:
public class MyAttributeFormatter(MyAttribute attribute) : IValidationAttributeFormatter
{
    public string FormatErrorMessage(CultureInfo culture, string messageTemplate, string displayName)
        => string.Format(culture, messageTemplate, displayName, attribute.CustomProperty);
}

// Register it in Program.cs:
builder.Services.AddValidationLocalization(options =>
    options.AttributeFormatters.AddFormatter<MyAttribute>(
        attribute => new MyAttributeFormatter(attribute)));

方法

名稱 Description
FormatErrorMessage(CultureInfo, String, String)

格式化指定 messageTemplate 時,將屬性特定的參數替換在 displayName。

適用於