Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize ASP.NET Identity Core Username to allow special characters and space

I have changed my Register Action Method to accept user Name instead of Email.

if (ModelState.IsValid)
{
    var user = new ApplicationUser 
    {
        UserName = model.Name,
        Email = model.Email,
    };

But when I Enter Name in TextBox like Joe Smith It give me an error that is Invalid UserName. It is not allowing user Name to Accept White space. My Question is how can I modify the builtin User Name to allow space and special characters. I am using ASP.NET Core.

Thanks in Advance.

like image 631
Babar Avatar asked Dec 27 '17 07:12

Babar


3 Answers

You can set user validation rules configuring identity with options in your Startup.cs.

services.AddIdentity<ApplicationUser, IdentityRole>(options => {
    options.User.AllowedUserNameCharacters = "allowed characters here";
    options.User.RequireUniqueEmail = true/false;
});

Related resources:

Configure Identity

like image 91
dropoutcoder Avatar answered Nov 20 '22 11:11

dropoutcoder


So cloudikka's answer had it right. I'll just add explicitly (cloudikka's link explained it as well) that you need to list ALL the characters you want to allow (not just the whitespace or special characters), like this:

services.AddIdentity<ApplicationUser, IdentityRole>(options => {
    options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/ ";
});

and NOT this options.User.AllowedUserNameCharacters = " "; which means 'only whitespace characters allowed'. (I reckon this was Babar's problem.)

like image 10
bsigma1 Avatar answered Nov 20 '22 11:11

bsigma1


The proposed solution can be tricky if you have an exhaustive list of special characters to whitelist.

If you want to blacklist instead, disable the whitelist in startup.cs:

 services.AddIdentity<User, Role>(
                options =>
                {                        
                    options.User.AllowedUserNameCharacters = string.Empty;
                })

Then create your custom user validator

 public class UsernameValidator<TUser> : IUserValidator<TUser>
where TUser : User
{
    public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
    {                
        if (user.UserName.Any(x=>x ==':' || x == ';' || x == ' ' || x == ','))
        {
            return Task.FromResult(IdentityResult.Failed(new IdentityError
            {
                Code = "InvalidCharactersUsername",
                Description = "Username can not contain ':', ';', ' ' or ','"
            }));
        }
        return Task.FromResult(IdentityResult.Success);
    }        
}

Then add it to startup.cs:

 services.AddIdentity<User, Role>(
                options =>
                {
                    options.Password = new PasswordOptions
                    {
                        RequiredLength = 8,
                        RequireUppercase = true,
                        RequireNonAlphanumeric = true,
                        RequireDigit = true,
                        RequireLowercase = true
                    };
                    options.User.AllowedUserNameCharacters = string.Empty;
                }).AddUserValidator<UsernameValidator<User>>()
like image 4
Jean-Simon Collard Avatar answered Nov 20 '22 12:11

Jean-Simon Collard