2

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:

  • Name xxxxx is already taken.

Tks.

Onaiggac
  • 551
  • 1
  • 6
  • 21
  • 1
    refer http://stackoverflow.com/questions/20452352/issue-with-username-validation-message-in-asp-net-identity – Vivekh Sep 30 '14 at 05:57

1 Answers1

7

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.

Community
  • 1
  • 1
Jason
  • 396
  • 1
  • 3
  • 17
  • 1
    I had tryed these two tips without success, but, now I try a different way for the second one and works fine. I am just created the new class (CustomUserValidator) and in Register action on AccountController I set the UserManager.UserValidator = new CustomUserValidator(UserManager); before the CreateAsync call. – Onaiggac Oct 06 '14 at 16:53