I created custom password validator to check the entering password by using my own regular expression. But when I testing it, the default error message is displayed first, and then mine. And I don't understand how to remove this default message, so that only mine remains. My message is "Your password is incorrect".
And there is a code:
Validator:
{
public Task<IdentityResult> ValidateAsync(UserManager<User> manager, User user, string password)
{
List<IdentityError> errors = new List<IdentityError>();
string pattern = "^(?=^.{12,}$)(?=.*[0-9]+)(?=.*[A-Z]+)(?=.*[a-z]+)(?=.*[&@^$%]+).*$";
if (!Regex.IsMatch(password, pattern))
{
return Task.FromResult(IdentityResult.Failed(new IdentityError
{
Code = "IncPass",
Description = "Your password is incorrect"
})) ;
}
return Task.FromResult(IdentityResult.Success);
}
}
Controller methods
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
User user = new User { Email = model.Email, UserName = model.Email, Year = model.Year };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
return View(model);
}
Startup
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders()
.AddPasswordValidator<CustomPasswordValidator>();
As soon as you call AddIdentity
the default password validator is registered, even when you provide a additional password validator.
You need to register your password validator before calling AddIdentity
like so:
services.TryAddScoped<IPasswordValidator<User>, CustomPasswordValidator>();
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<ApplicationContext>()
.AddDefaultTokenProviders();
As you can see, you then don't need the AddPasswordValidator
call anymore.
The default PasswordValidator
depends on a class called IdentityErrorDescriber
.
Although it looks possible to override the implementation, it seems this is intended for localization and might be difficult to achieve what you intend.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.