I'm trying to set the UserValidator
for the default ApplicationUserManager
in a new ASP.NET MVC 5 project (using ASP.NET Identity 2). I've created a very simple UserValidator:
public class SimpleUserValidator<TUser, TKey> : IIdentityValidator<TUser> where TUser: class, IUser<TKey> where TKey : IEquatable<TKey> {
private readonly UserManager<TUser, TKey> _manager;
public SimpleUserValidator(UserManager<TUser, TKey> manager) {
_manager = manager;
}
public async Task<IdentityResult> ValidateAsync(TUser item) {
var errors = new List<string>();
if (string.IsNullOrWhiteSpace(item.UserName))
errors.Add("Username is required");
if (_manager != null) {
var otherAccount = await _manager.FindByNameAsync(item.UserName);
if (otherAccount != null && !otherAccount.Id.Equals(item.Id))
errors.Add("Select a different username. An account has already been created with this username.");
}
return errors.Any()
? IdentityResult.Failed(errors.ToArray())
: IdentityResult.Success;
}
}
I set this by calling:
manager.UserValidator = new SimpleUserValidator<ApplicationUser, int>(manager);
within the ApplicationUserManager.Create()
method.
The problem is, this doesn't change the behavior. I still get the default The Email field is not a valid e-mail address
message. Is this not the correct place to set that validation?