How to change default error messages of MVC Core V

2019-04-06 11:39发布

Using MVC Core with ASP.NET Identity I would like to change the defaults error messages of ValidationSummary that arrived from Register action. Any advice will be much appreciated.

ASP.NET Core Register Action

2条回答
别忘想泡老子
2楼-- · 2019-04-06 11:53

You should override methods of IdentityErrorDescriber to change identity error messages.

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

In Startup.cs set IdentityErrorDescriber

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

The answer is from https://stackoverflow.com/a/38199890/5426333

查看更多
对你真心纯属浪费
3楼-- · 2019-04-06 12:11

You can use DataAnnotations in your RegisterViewModel class. In fact if you scaffold your application with authentication, you will get something like this:

    [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; }

Obviously, you can change ErrorMessage to anything you want it to be!

查看更多
登录 后发表回答