Username and email policy in ASP.NET Identity

Introduction


Besides user passwords, ASP.NET Identity implements also some default policies for usernames and email addresses.

For example, we have a stored user with test@gmail.com as an email address.

user data

If we try to insert another user with the same email address, we will get an error message :

invalid email error message

This default configuration is defined in the IdentityConfig.cs file.

Custom username and email policies


In order to implement a custom username or email policy in ASP.NET Identity, we use the UserValidator object.


manager.UserValidator = new UserValidator(manager)
{
    AllowOnlyAlphanumericUserNames = false,
    RequireUniqueEmail = true
};

AllowOnlyAlphanumericUserNames Allow only letters or digits in the usernames
RequireUniqueEmail Require a unique email address

In order to define your own validation logic for usernames and emails, go to App_Start > IdentityConfig.cs and override the values of the above properties.

Example


Setting the value of the AllowOnlyAlphanumericUserNames property to true .


manager.UserValidator = new UserValidator(manager)
{
    AllowOnlyAlphanumericUserNames = true,
    RequireUniqueEmail = true
};

With this configuration, If we try to add a user with a username containing special characters, we will get an error message :

invalid username error message