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>>()