Reputation: 3630
Perhaps my googlin' skills are not so great this morning, but I can't seem to find how to set up different password requirements (rather than min/max length) with a new asp.net mvc5 project using individual user accounts.
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
I don't know what password requirements I want to do just yet, but likely a combination of min length and requiring one lowercase, on capital letter, and a number.
Any idea how I can accomplish this (via model attributes preferably)?
Upvotes: 40
Views: 26512
Reputation: 19
/*Passwords must be at least min. 8 and max. 16 characters in length,
minimum of 1 lower case letter [a-z] and
a minimum of 1 upper case letter [A-Z] and
a minimum of 1 numeric character [0-9] and
a minimum of 1 special character: $ @ $ ! % * ? & + = #
PASSWORD EXAMPLE : @Password1
*/
pass = TextBoxPss1.Text;
Regex regex = new Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[$@$!%*?&+=#]) [A-Za-z\\d$@$!%*?&+=#]{8,16}$");
Match match = regex.Match(pass);
if (match.Success)
{TextBoxPss1.Text = "OK" }
Upvotes: 0
Reputation: 1706
You can configure password requirements in App_Start\IdentityConfig.cs
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 4,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
Upvotes: 110
Reputation: 1262
Another option is to create an implementation of IIdentityValidator<string>
and assign it to the PasswordValidator
property of your UserManager
. It only has one method, ValidateAsync
and you can define any sort of password validation you like in there.. I know this doesn't have some of the same advantages as using attributes in you model class as far as automatic client side validation, but just thought I would put this out there as an alternate for anyone who comes along.
e.g.
public class CustomPasswordValidator : IIdentityValidator<string>
{
public int MinimumLength { get; private set; }
public int MaximumLength { get; private set; }
public CustomPasswordValidator(int minimumLength, int maximumLength)
{
this.MinimumLength = minimumLength;
this.MaximumLength = maximumLength;
}
public Task<IdentityResult> ValidateAsync(string item)
{
if (!string.IsNullOrWhiteSpace(item)
&& item.Trim().Length >= MinimumLength
&& item.Trim().Length <= MaximumLength)
return Task.FromResult(IdentityResult.Success);
else return Task.FromResult(IdentityResult.Failed("Password did not meet requrements."));
}
}
Upvotes: 9
Reputation: 1355
You could use the RegularExpressionAttribute together with the rules from this answer:
Regex to validate password strength
Upvotes: 7