在 Blazor CRUD 组件的 handleSubmit 函数中,我必须提供基于
DataAnnotation MaxLength-attribute
的错误消息。我想显示一个“自定义”C# 错误消息,如下所示,其中“??”来自 MaxLength 属性:
$"The 'Vehicle Number' is limited to {??} characters."
CRUD 模型中的 DataAnnotation 是:
[Display(Name = "Vehicle Number")]
[MaxLength(12, ErrorMessage = "'{0}' is limited to {1} characters.")]
public string? TXT_VHCL_NUMBER { get; set; }
我知道
namespace is System.ComponentModel.DataAnnotations
应该具有该值,但我不知道如何获取与特定 DataAnnotation MaxLength 属性关联的“车辆编号字段”。
要利用
MaxLengthAttribute
的自定义验证消息的最大长度值,您需要使用 {1}
占位符。然后,验证器本身将在运行时将其替换为实际数字。
例如:
$"The 'Vehicle Number' is limited to {1} characters."
请注意,您还可以使用替换
{0}
自动获取正在验证的属性的名称,因此您实际上可以用更通用的模板替换自定义消息:
$"The '{0}' is limited to {1} characters."
当然,您不会以这种方式获得单词之间的空格,因为它将按原样使用您的属性名称,而不对其进行任何转换。
这是查看如何将这些值传递到格式字符串的简单方法:
/// <summary>
/// Applies formatting to a specified error message. (Overrides <see cref = "ValidationAttribute.FormatErrorMessage" />)
/// </summary>
/// <param name = "name">The name to include in the formatted string.</param>
/// <returns>A localized string to describe the maximum acceptable length.</returns>
public override string FormatErrorMessage(string name) {
// An error occurred, so we know the value is greater than the maximum if it was specified
return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
}
特别要注意那里
name
和 Length
值的位置,它们与格式字符串中的索引 0 和 1 一致。