How to customize ASP.NET Identity Core Username to allow special characters and space
Solution 1
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:
Solution 2
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.)
Solution 3
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>>()
Solution 4
services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.AllowedUserNameCharacters = String.Empty; options.User.RequireUniqueEmail = true; })
.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
Babar
Updated on July 28, 2022Comments
-
Babar almost 2 years
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.
-
Babar over 6 yearsI just want to store full Name First Name + Last Name in table and It has to a space between them.
-
AJ - over 6 yearsThen as I told you keep username as is and use a new property FullName in ApplicationUser class
-
Babar over 6 yearsOk How can I allow duplicate username? Is this possible?
-
dropoutcoder over 6 years@Jaffal: Whitesoace is bad practice because username is handle and it is used in the address bar and Joe%20Smith is ugly. Special characters can make web page behave strange(? querystring, # fragment). That is why we are not using special characters in general. Also special characters are not exactly human friendly and readable. Except _ or -.
-
dropoutcoder over 6 years@Babar It is not good idea to have duplicity in usernames. Username is handle and have to be unique.
-
AJ - over 6 years@cloudikka that's why I told Babar to keep username as is and use new property call it FullName for the purpose he wants and username will stay as is unique doesn't accept special characters or whitespaces Babar just create new property inside ApplicationUser
-
dropoutcoder over 6 years@Jaffal: I just extend your comment! I didnt meant to disagree with you.
-
Babar over 6 yearsIt is not allowing white space and special characters
-
dropoutcoder over 6 yearsI am reviewing the ASP.NET Identity source code and see nothing that will ban whitespace from usage, if you specify one in the AllowedUserNameCharacters property.
-
Babar over 6 yearsI always get that error 'Invalid UserName' either I use space or not. Code is not even working with plain character.
-
dropoutcoder over 6 yearsWithout the code it will be hard to find out for anyone.
-
Mog0 almost 6 yearsI found that I needed to support a wide variety of characters as they already existed in customer installs so this worked best for me - It disables the checking on user names.
-
James Rao over 2 yearsthis should be marked as answer. it works for me. the AllowedUserNameCharacters should be set with ALL characters we want to allow.