• Skip to primary navigation
  • Skip to main content

RocketGeek

Home of WP-Members, The Original WordPress Membership Plugin

  • WordPress Plugins
    • WP-Members
      • FAQs
      • Quick Start
      • Documentation
      • Extensions
    • Advanced Options
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Download Protect
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Invite Codes
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • MailChimp Integration
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • PayPal Subscriptions
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Salesforce Web-to-Lead
    • Security
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Text Editor
      • Purchase the Plugin
      • Get the Pro Bundle
    • User List
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • User Tracking
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Memberships for WooCommerce
    • WordPass
  • Store
    • Cart
    • Checkout
  • Blog
    • Basics [Free]
    • Tips and Tricks
    • Filters
    • Actions
    • Code Snippets
    • Shortcodes
    • Design
    • Release Announcements
  • Contact
  • Sign In
  • Show Search
Hide Search
Home » Filters » Create a rule for updated passwords to meet certain requirements

Create a rule for updated passwords to meet certain requirements

Chad Butler · Apr 3, 2012 ·

Recently, I had a user ask if it was possible to require that a password meet certain parameters.  Specifically, his client wanted to require that passwords contained at least 2 uppercase characters, 2 lowercase, 2 numbers, and 2 special characters.  Lastly, the password must be at least 8 characters long.  Working together, we were able to come up with a little customization that would not only suit the clients requirements, but also would require minimal effort to maintain.

A primary consideration when customizing this (or any) plugin is how hard will it be to upgrade the plugin.  WP-Members has a number of features to make this process more flexible. Much like WP itself, WP-Members uses filter and action hooks which allows you to upgrade the plugin without overriding your customization. 

This article is only available to WP-Members Support Subscribers. If you have an existing subscription, please login below. If you do not have a current support subscription, you can purchase a support subscription here.

Already a Member? Log In Here
   
Forgot password? Click here to reset

To gain full access to WP-Members premium content, a current support subscription is required. You can purchase an annual support subscription for as little as $59, which provides you with access to priority support, a customer support forum, access to code snippets, and more.

Why wait? Choose your subscription option here.

[
Why join?]

Filters customization, str_replace, wpmem_login_form_before, wpmem_msg_dialog, wpmem_pwd_change_error

Welcome to RocketGeek Interactive › Forums › Create a rule for updated passwords to meet certain requirements

Tagged: customization, str_replace, wpmem_login_form_before, wpmem_msg_dialog, wpmem_pwd_change_error

  • This topic has 12 replies, 3 voices, and was last updated 2 years, 5 months ago by Chad Butler.
Viewing 8 reply threads
  • Author
    Posts
    • May 25, 2012 at 8:38 am #723
      Chad Butler
      Keymaster

      Recently, I had a user ask if it was possible to require that a password meet certain parameters.  Specifically, his client wanted to require that pas
      [See the full post at: Create a rule for updated passwords to meet certain requirements]

    • September 22, 2017 at 8:29 am #13643
      rw20ces
      Participant

      change error message:
      if you have multiple languages on your site its better to use $str = __(‘pwd-criteria’, ‘your-theme’) instead of the str_replace()

      of course this is only one third of what has to be done. you should validate your password rule

      1/ on registration
      2/ on password reset, choose new password (wp-members can’t do this for some strange reason)
      3/ password change, when logged in (as written in this article)

      • This reply was modified 3 years, 5 months ago by rw20ces.
      • This reply was modified 3 years, 5 months ago by rw20ces.
      • This reply was modified 3 years, 5 months ago by Chad Butler.
    • September 22, 2017 at 9:00 am #13646
      rw20ces
      Participant

      for problem 1/ i found this to work:

      
      /* have at least 8 chars consisting of letters and numbers */
      function check_pwd_criteria($pwd){
          if(strlen( $pwd ) < 8) return false;
          if(preg_match_all('/[A-Za-z]/', $pwd) < 1 ) return false;
          if(preg_match_all('/[0-9]/', $pwd) < 1 ) return false;
          return true;
      }
      
      add_filter( 'wpmem_register_data', 'my_register_data_filter', 10, 2 );
      
      function my_register_data_filter( $fields, $toggle ) {
          global $pwdcriteria;
          global $wpmem_themsg;
      
          if ( 'new' == $toggle ) {
              if(!check_pwd_criteria($fields['password'])){
                  $pwdcriteria = true;
                  $wpmem_themsg = "pwdcriteriaerr";
              }
          }
       
          if ( 'edit' == $toggle ) {
              // This is a user profile edit
          }
       
          return $fields;
      }
    • September 23, 2017 at 9:46 am #13656
      Chad Butler
      Keymaster

      Let me address this part first:

      if you have multiple languages on your site its better to use $str = __(‘pwd-criteria’, ‘your-theme’) instead of the str_replace()

      Actually, str_replace() is what you need to use here. WP’s internationalization functions (__(), _e(), etc) can still be used along with str_replace(). One is for replacing specific text (str_replace()), and one is for internationalizing it (__()). They don’t serve the same purpose.

      In this instance, str_replace() is looking for a specific string (“Passwords did not match.”) in the error message because we are going to change it. What this actual string is depends on the following:

      • What the actual dialog for “Passwords did not match” is in the plugin’s Dialogs tab (since this can be customized by the site user).
      • Whether it needs to be internationcalized/localized (i.e. whether another lanuguage or multiple languages is/are used).
      • A combination of these two.

      In general, in a single language site that is not English, this section of the filter would look as follows:

      $old = __( "Passwords did not match.<br /><br />Please try again.", 'wp-members' );
      // In a single language site, directly translate the following accordingly.
      $new = "Your password did not meet the criteria of 
         containing at least 2 uppercase letters, two 
         lowercase letters, 2 numbers, and 2 special 
         characters.<br /><br />Please try again.";
      $str = str_replace( $old, $new, $str );

      First note how $old is constructed. We need the original string so we can properly replace it with a more relevant message (i.e. that the password did not meet the requirements). This is where internationalization is used to find the correct string.

      Secondly note the $new variable. It is not translated using internationalization. It could be, and in a multi-language site it would have to be. But that adds some complexity that needs to be managed because your translation files would not have this string in them to serve to the user. You would need to add this string and compile a new custom translation file. If it is a single language site, that’s not necessary. It is better to simply serve the correct translated string (meaning: change the English in the example to suit the needed language).

      Then finally, str_replace() is run to search the string and do the search/replace accordingly.

      I hope this explains not only how to properly handle it, but also “why” to do it this way.

      • This reply was modified 3 years, 5 months ago by Chad Butler.
      • This reply was modified 3 years, 5 months ago by Chad Butler.
    • September 23, 2017 at 11:04 am #13659
      Chad Butler
      Keymaster

      of course this is only one third of what has to be done. you should validate your password rule

      1/ on registration
      2/ on password reset, choose new password (wp-members can’t do this for some strange reason)
      3/ password change, when logged in (as written in this article)

      It’s interesting that you bring up this question as I recently was also asked pretty much the same thing recently via email support. It’s weird, but many times these types of questions come in pairs or more (meaning I get the same question from several users all at the same time). The generally means it’s time to re-address the original article and maybe update it.

      Here was part of the explanation to this other user that should shed some light:

      When [this] particular post was originally written, the only option for the plugin’s registration was to email a randomly generated password to the user. Adding a password field to the registration process was a custom process. As such, for the subscriber question that generated that particular post, it was expected that the user would receive the random password, login and change their password on first use (and would then need to create a password using the password rules).

      In addition to this, the random password would have met the password requirements as well because the WP random password generator was generating passwords that met the kind of criteria in the example. WP’s random password process has changed somewhat since then as well (although, unless filtered, it generates only strong passwords based on the WP password strength algorithm).

      A simple filter to address the password at registration (#1 above), assuming that a password is chosen at registration, would be as follows:

      add_filter( 'wpmem_pre_register_data', function( $fields ) {
      	
      	global $wpmem_themsg;
      	
      	$password = $fields['password'];
      	
      	if ( $password ) {
      		// Check for proper password strength.
      		switch ( $password ) {
      			// Must have 2 Uppercase characters
      			case ( preg_match_all( '/[A-Z]/', $password, $o ) < 2 ):
      			// Must have 2 lowercase characters
      			case ( preg_match_all( '/[a-z]/', $password, $o ) < 2 ):
      			// Must have 2 numeric characters
      			case ( preg_match_all( '/[0-9]/', $password, $o ) < 2 ):
      			// Must have 2 special chars
      			case ( preg_match_all( '/[^a-zA-Z0-9]/', $password, $o ) < 2 ):
      			// Must be at least 8 characters.
      			case ( strlen( $password ) < 8 ):
      				$wpmem_themsg = "Sorry, your password did not meet the password requirements. Please try again.";
      				break;
      		}		
      	}
      	
      });

      In order to address #2 as needed, either a filter for WP’s random_password hook or a pluggable function of wp_generate_password() – either of which would need to check the criteria. I’ll need to put together a working example of that. Once I do, I’ll probably update this entire article accordingly.

    • September 24, 2018 at 8:07 pm #15437
      FARA
      Participant

      I would like to do something like this. I my case there is no registration process being used. Only when a person resets or changes their password. Which hook would it go into? There are several, I didn’t know if it is one or two? You show in the above example wpmem_pre_register_data which is registration. Only want to do a simple sanity check on a couple things. Thank you!
      Kevin

      • September 25, 2018 at 7:52 am #15444
        Chad Butler
        Keymaster

        Hi Kevin,

        The code snippet in the actual tutorial article is only for password changes. So that’s all you need if you’re not worried about setting it at registration. The discussion in the associated forum thread regarding registration are for folks who not only have/allow registration, but they also have the user create a password when they register (so that would need to apply the password rules as well).

        Hope that clarifies.

    • September 25, 2018 at 10:37 am #15452
      FARA
      Participant

      Chad,
      Thanks. Didn’t find the associated one. This is perfect. THank you.
      Kevin

      • September 25, 2018 at 1:01 pm #15460
        Chad Butler
        Keymaster

        No problem!

    • September 25, 2018 at 4:32 pm #15461
      FARA
      Participant

      Forgive me if I am missing something. In the original tutorial you have two examples displaying the error. The second is supposed to run if “so we grab that with $_REQUEST and set it as our condition.”. I see no difference at all in the code examples. They are both referencing the same hook and have the same conditions. So why two and not one? Not sure what is different.

      • September 25, 2018 at 4:57 pm #15462
        Chad Butler
        Keymaster

        Hmmm… that might be poor editing on my part with whenever the last update of the article was. I’ll need to dig into it, because both of the message code snippets are exactly the same. I may be re-editing this one tonight 😉

    • September 25, 2018 at 6:35 pm #15463
      FARA
      Participant

      Sounds good Chad. I am getting to that age that I don’t always trust myself! Thanks!

      • September 25, 2018 at 7:40 pm #15466
        Chad Butler
        Keymaster

        Thanks for bringing this one up. I actually hadn’t noticed it, but reading the content I did recall what was supposed to be in that second filter – it was to put some “helper” text above the password change form to indicate what the password rules are.

        Originally, based on the text, the filter was using the wpmem_login_form filter to add some HTML above the form. It used $_REQUEST to check for the action to be “pwdchange” and only add it if that was true (so it would only be adding it when the form was the password change form).

        That was OK… but since I was updating it, I didn’t exactly like how the rules text was above the heading of the form. So instead of recreating what was there before, I went a slightly different direction. I used wpmem_login_form_args (which didn’t exist when this article was originally written) to slip some additional HTML into the form’s default HTML. That way we could get it in between the heading and the input fields. That looks a little better, I think.

        Anyway… it should make a little more sense now. It’s an optional filter, but it does give things a little more polish since you’re telling the user what is expected *before* they enter a new password.

  • Author
    Posts
Viewing 8 reply threads
  • You must be logged in to reply to this topic.
Log In

Ready to get started?

Join Today!

© 2021 · butlerblog.com · RocketGeek is built using WordPress, WP-Members, and the Genesis Framework

  • butlerblog.com
  • WP-Members Support Subscription
  • Terms of Service
  • Refund Policy