简体   繁体   中英

How to apply a password policy validation on custom form in drupal 8?

I want to apply password policy module functionality on custom password reset form on drupal 8. Its not working for my reset form. Note: '#type' => 'password_confirm' has set to the form as below,

    "#type" => "password_confirm"
    "#size" => 25
    "#description" => Drupal\Core\StringTranslation\TranslatableMarkup {#1612 ▶}
    "#attributes" => array:1 [▶]
  ]```
still its not working.
And, one point I noticed, Custom form act as Anonymous user.
function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    
    if ($form_id == 'user_pass_reset') { 
      
      $form['#validate'][] = '_form_custom_validation';
      
    }
}

//CUSTOM FUNCTION TO CHECK PASSWORD COMPLEXITY
function _form_custom_validation(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  
  if ($form_state->hasValue('pass')) {
     $pass = $form_state->getValue('pass');
     $pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[-+_!@#$%^&*.,?]).+$";
     if (!preg_match('/[a-z]+/', $pass)) {
        $form_state->setErrorByName('title', t('Your password must contain Uppercase, lowercase, numeric and special character.'));
     }
      if (!preg_match('/[A-Z]+/', $pass)) {
        $form_state->setErrorByName('title', t('Your password must contain Uppercase, lowercase, numeric and special character.'));
     }
      if (!preg_match('/[0-9]/', $pass)) {
        $form_state->setErrorByName('title', t('Your password must contain Uppercase, lowercase, numeric and special character.'));
     }
      if (!preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $pass)) {
        $form_state->setErrorByName('title', t('Your password must contain Uppercase, lowercase, numeric and special character.'));
     }
     
     if (strlen($pass) < 8) {
        $form_state->setErrorByName('title', t('Your password must contain atleast 8 characters.'));
     }

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM