Skip to content

Instantly share code, notes, and snippets.

@blachniet
Last active November 3, 2017 04:06
Show Gist options
  • Save blachniet/7394005 to your computer and use it in GitHub Desktop.
Save blachniet/7394005 to your computer and use it in GitHub Desktop.
This custom user validator can be used instead of the default user validator in order to require that the UserName property in the IUser be an email address. To use this validator, just set UserManager.UserValidator to a new instance of this class.
/// <summary>
/// A replacement for the <see cref="UserValidator"/> which requires that an email
/// address be used for the <see cref="IUser.UserName"/> field.
/// </summary>
/// <typeparam name="TUser">Must be a type derived from <see cref="Microsoft.AspNet.Identity.IUser"/>.</typeparam>
/// <remarks>
/// This validator check the <see cref="IUser.UserName"/> property against the simple email regex provided at
/// http://www.regular-expressions.info/email.html. If a <see cref="UserManager"/> is provided in the constructor,
/// it will also ensure that the email address is not already being used by another account in the manager.
///
/// To use this validator, just set <see cref="UserManager.UserValidator"/> to a new instance of this class.
/// </remarks>
public class CustomUserValidator<TUser> : IIdentityValidator<TUser>
where TUser : Microsoft.AspNet.Identity.IUser
{
private static readonly Regex EmailRegex = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly UserManager<TUser> _manager;
public CustomUserValidator()
{
}
public CustomUserValidator(UserManager<TUser> manager)
{
_manager = manager;
}
public async Task<IdentityResult> ValidateAsync(TUser item)
{
var errors = new List<string>();
if (!EmailRegex.IsMatch(item.UserName))
errors.Add("Enter a valid email address.");
if (_manager != null)
{
var otherAccount = await _manager.FindByNameAsync(item.UserName);
if (otherAccount != null && otherAccount.Id != item.Id)
errors.Add("Select a different email address. An account has already been created with this email address.");
}
return errors.Any()
? IdentityResult.Failed(errors.ToArray())
: IdentityResult.Success;
}
}
@Legends
Copy link

Legends commented Apr 16, 2016

Add constraint class like this:
public class CustomUserValidator<TUser> : IIdentityValidator<TUser> where TUser : class, Microsoft.AspNet.Identity.IUser

@Legends
Copy link

Legends commented Apr 17, 2016

remove the default constructor...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment