小编JIg*_*gsB的帖子

.Net Core 中的自定义属性未显示验证消息

我正在创建用于验证的自定义属性以覆盖 .Net Core 中的 RegularExpressionAttribute,并为客户端验证实现 IClientModelValidator。验证适用于字段,但未显示错误消息。ModelState.IsValid 也给出了 Invalid 该字段,但未显示验证消息。

视图模型

[Required]
[Display(Name = "First Name")]
[RestrictSplCharacters]
public string FirstName { get; set; }
Run Code Online (Sandbox Code Playgroud)

覆盖属性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class RestrictSplCharactersAttribute : RegularExpressionAttribute, IClientModelValidator
{
   private string errorMessage= "Special characters or blank space is not allowed in {0}";

public RestrictSplCharactersAttribute()
    : base(@"[_A-z0-9]*((-|\s)*[_A-z0-9])*$")
{
    this.ErrorMessage = this.errorMessage;
}

public void AddValidation(ClientModelValidationContext context)
{
    MergeAttribute(context.Attributes, "data-val", "true");
    var errorMessage = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
    MergeAttribute(context.Attributes, "data-val-restrictSplCharacters", errorMessage);
}

private bool MergeAttribute(
    IDictionary<string, …
Run Code Online (Sandbox Code Playgroud)

javascript data-annotations .net-core

5
推荐指数
1
解决办法
400
查看次数

标签 统计

.net-core ×1

data-annotations ×1

javascript ×1