Search code examples
asp.net-mvc-5asp.net-membership

Where to set MembershipPassword() requirments?


The selected answer here shows one method of how the requirments can be set but I am looking to make those rules more reusable while still using the MembeshipPassowrd() validation attribute and I think it can be done by specifying the roles within my extended membership provider but I can't find any documentation on how this can be done.

How do I include the password requirments within my custom/extended membership provider?

Model

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[MembershipPassword(
    MinRequiredNonAlphanumericCharacters = 1,
    MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, etc).",
    ErrorMessage = "Your password must be 6 characters long and contain at least one symbol (!, @, #, etc)."
)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

Solution

  • Seems like the PasswordStrngthRegularExpression is what is required to do this, it can either be set in the web.config file or within the extended membership provider by overriding it:

    public override string PasswordStrengthRegularExpression
    {
        get { return @"(?=.{5,})(?=(.*\d){1,})(?=(.*\W){1,})(?=.*[a-z])(?=.*[A-Z])"; }
    }
    

    OR

    <membership defaultProvider="SqlProvider"
      userIsOnlineTimeWindow = "20>
      <providers>
        <add
          name="SqlProvider"
          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="SqlServices"
          requiresQuestionAndAnswer="true"
          passwordStrengthRegularExpression="@\"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})"
          />
      </providers>
    </membership>
    

    MSDN Has details on this.