【问题标题】:How to change default error messages of MVC Core ValidationSummary?如何更改 MVC Core ValidationSummary 的默认错误消息?
【发布时间】:2016-12-22 09:18:36
【问题描述】:

使用带有 ASP.NET Identity 的 MVC Core 我想更改从注册操作到达的 ValidationSummary 的默认错误消息。 任何建议将不胜感激。

【问题讨论】:

  • 您可以从模型类更改此消息
  • 您应该能够使用 DataAnnotation 中的属性 ErrorMessage = "..." 更改 AccountViewModel.cs 中的这些错误消息。

标签: asp.net-mvc asp.net-core asp.net-identity


【解决方案1】:

您应该重写IdentityErrorDescriber 的方法来更改身份错误消息。

public class YourIdentityErrorDescriber : IdentityErrorDescriber
{
    public override IdentityError PasswordRequiresUpper() 
    { 
       return new IdentityError 
       { 
           Code = nameof(PasswordRequiresUpper),
           Description = "<your error message>"
       }; 
    }
    //... other methods
}

Startup.cs 中设置IdentityErrorDescriber

public void ConfigureServices(IServiceCollection services)
{
    // ...   
    services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddErrorDescriber<YourIdentityErrorDescriber>();
}

答案来自https://stackoverflow.com/a/38199890/5426333

【讨论】:

    【解决方案2】:

    您可以在 RegisterViewModel 类中使用 DataAnnotations。事实上,如果您使用身份验证构建应用程序,您将得到如下结果:

        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    

    显然,您可以将ErrorMessage 更改为您想要的任何内容!

    【讨论】:

    • 嗨 Felix 更改 DataAnnotations 不会影响验证摘要。
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 2017-03-09
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2021-12-30
    相关资源
    最近更新 更多