Search code examples
asp.net-coreasp.net-identityidentity

Where can i find a List of IdentityErrors related to User registration?


I want to try to filter the Identity Errors during the Sign Up process, so then i can show them in a more friendly way in the View for instance behind the respective input, and not showing them by using asp-validation-summary="All".
See the below code as a reference

[HttpPost]
public async Task<IActionResult> SignUp(SignUpViewModel viewModel)
{
    var usernameErrors = new List<string>();
    var passwordErrors = new List<string>();
    var unknowErrors = new List<string>();
    if (ModelState.IsValid)
    {
        var client = new Client
        {
            UserName = viewModel.Id, FullName = viewModel.FullName, BirthDate = viewModel.BirthDate.Value,
            Email = viewModel.Email
        };
        var result = await _userManager.CreateAsync(client, viewModel.Password);
        if (result.Succeeded)
            return RedirectToAction("SignIn", new {DidHeJustSignUp = true});

        foreach (var error in result.Errors)
        {
            if(error.Code.Contains("UserName"))
                usernameErrors.Add(error.Description);
            if(error.Code.Contains("Password"))
                passwordErrors.Add(error.Description);
            if(error.Code.Contains("unknownError"))
                unknowErrors.Add(error.Description);
        }
        viewModel.UsernameErrors = usernameErrors;
        viewModel.PasswordErrors = passwordErrors;
        viewModel.UnknowErrors = unknowErrors;
    }

    return View(viewModel);
}

I'm not trying to filter all but at least the most obvious ones. I'm new to Identity so my apologyze if the question is dumb for you.


Solution

  • As far as I know, the UserManager.CreateAsync method will call PasswordValidator and UserValidator method when creating user.

    So the normal error is as below:

    IdentityErrorDescriber.PasswordTooShort
    
    IdentityErrorDescriber.PasswordRequiresDigit
    
    IdentityErrorDescriber.PasswordRequiresLower
    
    IdentityErrorDescriber.PasswordRequiresUpper
    
    IdentityErrorDescriber.PasswordRequiresUniqueChars
    
    IdentityErrorDescriber.InvalidUserName
    
    IdentityErrorDescriber.DuplicateUserName
    

    If you have enabled the require Email opinion add below check:

    IdentityErrorDescriber.InvalidEmail
    
    IdentityErrorDescriber.DuplicateEmail