Onaiggac
Onaiggac

Reputation: 561

MVC 5 Identity and error message

I am using the Identity 2.0 and I want to know how to customize the error message when I try to register a user that already been registered. The follow message is what I receving:

Tks.

Upvotes: 2

Views: 5241

Answers (1)

Jason
Jason

Reputation: 416

I had a similar problem, this SO question and this blog helped me.

Applying these directly to your question, you can do it two ways. A quick way that solves this specific problem, and a more involved way that allows you to modify any other Identity errors in the future.

1.) The quick way: - Under Controllers/AccountController.cs modify the AddErrors(IdentityResult result) method. Change this:

    private void AddErrors(IdentityResult result)
    {
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error);
        }
    }

To this: Again, this code is a proposed answer from Marius in the question I referenced. I didn't use this myself, but looks like it should work.

private void AddErrors(IdentityResult result)
{
    foreach (var error in result.Errors)
    {
        if (error.StartsWith("Name"))
        {
            var NameToEmail= Regex.Replace(error,"Name","Email");
            ModelState.AddModelError("", NameToEmail);
        }
        else
        {
            ModelState.AddModelError("", error);
        }
    }
}
  1. A more maintainable and extensible solution is here on Brian Lachniet's blog. Josh's answer in the same question is the same thing, although Brian's blog explicitly describes how to implement replacing the UserValidator method.

    This is the method I followed, it works. As a bonus he keeps updating it, with the last change making it compatible with Identity 2.0 as of March 28th.

Upvotes: 7

Related Questions