Sabir Hossain
Sabir Hossain

Reputation: 1205

How to take Unicode characters as UserName in ASP.NET Core Mvc?

In my ASP.NET Core app I want to take UserName from other language than English but when I try to create an user I got the error

"User name 'myUnicodeLang' is invalid, can only contain letters or digits."

How can I allow Unicode characters for my UserManager? I found a question that how to take email as UserName and the solution was.

UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) 
{ 
    AllowOnlyAlphanumericUserNames = false 
};

but it's not working in my project it says Using the Generic Type UserManager<TUser> requires 1 type argument

#Edit

Controller Constructor

public AuthController(UserManager<SchoolUser> userManager,
        SignInManager<SchoolUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;

        //Error here
        UserManager.UserValidator = new UserValidator<SchoolUser>
        (userManager) 
         { 
           AllowOnlyAlphanumericUserNames = false };
         }
     }

Upvotes: 0

Views: 3189

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131180

The code in the question looks like an attempt to add ASP.NET MVC code into a Core MVC project. That won't work because in ASP.NET Core MVC the UserManager doesn't have a UserValidator property. It has a UserValidators collection that allows adding multiple custom validators.

The UserValidator has also changed and doesn't contain any configuration settings itself.

The easiest way to configure the allowable characters is to use the AddIdentity() overload in Startup.ConfigureServices that allows setting properties. Replace :

services.AddIdentity<ApplicationUser, IdentityRole>()

With

services.AddIdentity<ApplicationUser, IdentityRole>(options=>
{
    options.User.AllowedUserNameCharacters = "whatever";
})

The default value is "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+" which can handle most email addresses

You could append extra characters to this, eg:

services.AddIdentity<ApplicationUser, IdentityRole>(options=>
{
    var allowed = options.User.AllowedUserNameCharacters 
                  + "........";
    options.User.AllowedUserNameCharacters = allowed;
})

Upvotes: 3

Related Questions