Customizing user registration in MVC

   —   

By default, there are some restrictions on user names when registering in an MVC project. If you want to customize user name and password formats, a small code change is necessary.

If you've ever attempted to register a new user on your MVC site with a completely valid email address such as test+user@site.com, you would have seen this error message:

"User name test+user@site.com is invalid, can only contain letters or digits."

This is caused by the plus sign in the user name, as it can only contain alphanumeric characters and some special characters. When you enabled authentication and user registration in your MVC project, you added the following line to register the UserManager as outlined in our documentation:

app.CreatePerOwinContext(() => UserManager.Initialize(app, new UserManager(new UserStore(SiteContext.CurrentSiteName))));

The Initialize() method sets some properties of the UserManager with default settings:

manager.PasswordValidator = new PasswordValidator(); manager.UserLockoutEnabledByDefault = false; manager.UserValidator = new UserValidator<User, int>(manager);

To customize the UserValidator and change the AllowOnlyAlphanumericUserNames property, you can alter the CreatePerOwinContext() method and return a customized UserManager. In the following example, we are allowing special characters in user names and requiring at least one digit in passwords.

app.CreatePerOwinContext(() => { var um = UserManager.Initialize(app, new UserManager(new UserStore(SiteContext.CurrentSiteName))); // Allow special characters in user names var uv = new UserValidator<User, int>(um); uv.AllowOnlyAlphanumericUserNames = false; // Require at least one digit in passwords var pv = new PasswordValidator(); pv.RequireDigit = true; um.UserValidator = uv; um.PasswordValidator = pv; return um; });

Note that user names and passwords must still conform to the restrictions in Kentico's settings. To allow user names with special characters in them, you will need to use on the web.config keys listed here, such as CMSEnsureSafeUserNames or by creating a custom regex in the CMSUserValidationRegEx key.

Share this article on   LinkedIn