Class kartik\password\StrengthValidator

Inheritancekartik\password\StrengthValidator » yii\validators\Validator » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Uses Traitskartik\base\TranslationTrait
Available since version1.0

StrengthValidator validates if the attribute value matches a specified set of password strength rules. You can use this validator to validate the password strength as part of your model's validation rules.

For example,

// add this in your model
use kartik\password\StrengthValidator;

// use the validator in your model rules
public function rules() {
    return [
           [['username', 'password'], 'required'],
           [['password'], StrengthValidator::className(), 'preset'=>'normal', 'userAttribute'=>'username']
    ];
}

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$allowSpaces boolean Whether to allow spaces in the input. kartik\password\StrengthValidator
$allowSpacesError string User-defined error message used when $allowSpaces is false and spaces are found in input kartik\password\StrengthValidator
$apiHIBP string The api for "Have I Been Pwned" check with trailing slash kartik\password\StrengthValidator
$attributeNames array Attribute names. yii\validators\Validator
$attributes array|string Attributes to be validated by this validator. yii\validators\Validator
$behaviors yii\base\Behavior[] List of behaviors attached to this component. yii\base\Component
$builtInValidators array List of built-in validators (name => class or configuration) yii\validators\Validator
$digit integer Minimal number of numeric digit characters kartik\password\StrengthValidator
$digitError string User-defined error message used when value contains less than $digit characters kartik\password\StrengthValidator
$enableClientValidation boolean Whether to enable client-side validation for this validator. yii\validators\Validator
$encoding string The encoding of the string value to be validated (e.g. 'UTF-8'). kartik\password\StrengthValidator
$except array|string Scenarios that the validator should not be applied to. yii\validators\Validator
$hasEmail boolean Check whether password contains an email string kartik\password\StrengthValidator
$hasEmailError string User-defined error message used $hasEmail is true and value contains an email kartik\password\StrengthValidator
$hasUser boolean Check whether password contains the username kartik\password\StrengthValidator
$hasUserError string User-defined error message used when $hasUser is true and value contains the username kartik\password\StrengthValidator
$haveIBeenPwned boolean Whether to check the online database of "Have I Been Pwned" kartik\password\StrengthValidator
$haveIBeenPwnedError string User-defined error message used when password is found in Have I Been Pwned kartik\password\StrengthValidator
$i18n array The the internalization configuration for this widget. kartik\base\TranslationTrait
$isEmpty callable|null A PHP callable that replaces the default implementation of isEmpty(). yii\validators\Validator
$length integer|array Specifies the length limit of the value to be validated. kartik\password\StrengthValidator
$lengthError string User-defined error message used when the length of the value is not equal to $length. kartik\password\StrengthValidator
$lower integer Minimal number of lower case characters kartik\password\StrengthValidator
$lowerError string User-defined error message used when value contains less than $lower characters kartik\password\StrengthValidator
$max integer Maximum length. kartik\password\StrengthValidator
$maxError string User-defined error message used when the length of the value is greater than $max. kartik\password\StrengthValidator
$message string User-defined error message used when the value is not a string kartik\password\StrengthValidator
$min integer Minimum number of characters. kartik\password\StrengthValidator
$minError string User-defined error message used when the length of the value is smaller than $min. kartik\password\StrengthValidator
$on array|string Scenarios that the validator can be applied to. yii\validators\Validator
$preset string Preset - one of the preset constants. kartik\password\StrengthValidator
$presetsSource string Presets configuration source file defaults to [[presets. kartik\password\StrengthValidator
$repeat integer Maximum number of same characters that can be repeated kartik\password\StrengthValidator
$repeatError string User-defined error message used when the number of characters repeated exceeds $repeat. kartik\password\StrengthValidator
$skipOnEmpty boolean Whether this validation rule should be skipped if the attribute value is null or an empty string. yii\validators\Validator
$skipOnError boolean Whether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. yii\validators\Validator
$special integer Minimal number of special characters kartik\password\StrengthValidator
$specialError string User-defined error message used when value contains more than $special characters kartik\password\StrengthValidator
$strengthTarget array The target strength rule requirements that will be evaluated for displaying the strength meter kartik\password\StrengthValidator
$upper integer Minimal number of upper case characters kartik\password\StrengthValidator
$upperError string User-defined error message used when value contains less than $upper characters kartik\password\StrengthValidator
$userAttribute string The name of the username attribute kartik\password\StrengthValidator
$usernameValue string The value of the username to cross check for hasUser rule. kartik\password\StrengthValidator
$validationAttributes array List of attribute names. yii\validators\Validator
$when callable|null A PHP callable whose return value determines whether this validator should be applied. yii\validators\Validator
$whenClient string|null A JavaScript function name whose return value determines whether this validator should be applied on the client-side. yii\validators\Validator

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$_msgCat string Translation message file category name for i18n. kartik\base\TranslationTrait
$_rules array The default rule settings kartik\password\StrengthValidator

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\BaseObject
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
addError() Adds an error about the specified attribute to the model object. yii\validators\Validator
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\BaseObject
clientValidateAttribute() Returns the JavaScript needed for performing client-side validation. kartik\password\StrengthValidator
createValidator() Creates a validator object. yii\validators\Validator
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getAttributeNames() Returns cleaned attribute names without the ! character at the beginning. yii\validators\Validator
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getClientOptions() Returns the client-side validation options. yii\validators\Validator
getValidationAttributes() Returns a list of attributes this validator applies to. yii\validators\Validator
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. kartik\password\StrengthValidator
initI18N() Yii i18n messages configuration for generating translations kartik\base\TranslationTrait
isActive() Returns a value indicating whether the validator is active for the given scenario and attribute. yii\validators\Validator
isEmpty() Checks if the given value is empty. yii\validators\Validator
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
trigger() Triggers an event. yii\base\Component
validate() Validates a given value. yii\validators\Validator
validateAttribute() Validates a single attribute. kartik\password\StrengthValidator
validateAttributes() Validates the specified object. yii\validators\Validator

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
applyPreset() Apply preset parameter if set kartik\password\StrengthValidator
checkParams() Validates the provided parameters for valid data type and the right threshold for 'max' chars. kartik\password\StrengthValidator
formatMessage() Formats a mesage using the I18N, or simple strtr if \Yii::$app is not available. yii\validators\Validator
getRuleMessage() Gets the localized rule message kartik\password\StrengthValidator
performValidation() The main password validation routine kartik\password\StrengthValidator
setRuleMessages() Sets the rule message for each rule kartik\password\StrengthValidator
validateValue() Validates a value. kartik\password\StrengthValidator

Constants

Hide inherited constants

ConstantValueDescriptionDefined By
EMAIL_MATCH '/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i' kartik\password\StrengthValidator
FAIR 'fair' kartik\password\StrengthValidator
MEDIUM 'medium' kartik\password\StrengthValidator
NORMAL 'normal' kartik\password\StrengthValidator
RULE_EMAIL 'hasEmail' kartik\password\StrengthValidator
RULE_HIBP 'haveIBeenPwned' kartik\password\StrengthValidator
RULE_LEN 'length' kartik\password\StrengthValidator
RULE_LOW 'lower' kartik\password\StrengthValidator
RULE_MAX 'max' kartik\password\StrengthValidator
RULE_MIN 'min' kartik\password\StrengthValidator
RULE_NUM 'digit' kartik\password\StrengthValidator
RULE_REP 'repeat' kartik\password\StrengthValidator
RULE_SPACES 'allowSpaces' kartik\password\StrengthValidator
RULE_SPL 'special' kartik\password\StrengthValidator
RULE_UP 'upper' kartik\password\StrengthValidator
RULE_USER 'hasUser' kartik\password\StrengthValidator
SIMPLE 'simple' kartik\password\StrengthValidator
STRONG 'strong' kartik\password\StrengthValidator

Property Details

$_rules protected static property

The default rule settings

protected static array $_rules = [
    self::RULE_MIN => ['int' => true],
    
self::RULE_MAX => ['int' => true],
    
self::RULE_LEN => ['int' => true],
    
self::RULE_SPACES => ['bool' => true],
    
self::RULE_USER => ['bool' => true],
    
self::RULE_EMAIL => ['match' => self::EMAIL_MATCH'bool' => true],
    
self::RULE_LOW => ['match' => '![a-z]!''int' => true],
    
self::RULE_UP => ['match' => '![A-Z]!''int' => true],
    
self::RULE_NUM => ['match' => '![\d]!''int' => true],
    
self::RULE_SPL => ['match' => '![\W]!''int' => true],
    
self::RULE_REP => ['match' => '/(\w)\1{<REP>,}/'],
    
self::RULE_HIBP => ['bool' => true]
]
$allowSpaces public property

Whether to allow spaces in the input. Defaults to false.

public boolean $allowSpaces false
$allowSpacesError public property

User-defined error message used when $allowSpaces is false and spaces are found in input

public string $allowSpacesError null
$apiHIBP public property

The api for "Have I Been Pwned" check with trailing slash

See also https://haveibeenpwned.com/API/v3#SearchingPwnedPasswordsByRange.

public string $apiHIBP 'https://api.pwnedpasswords.com/range/'
$digit public property

Minimal number of numeric digit characters

public integer $digit 2
$digitError public property

User-defined error message used when value contains less than $digit characters

public string $digitError null
$encoding public property

The encoding of the string value to be validated (e.g. 'UTF-8'). If this property is not set,

[[\yii\base\Application::charset]] will be used.
public string $encoding null
$hasEmail public property

Check whether password contains an email string

public boolean $hasEmail true
$hasEmailError public property

User-defined error message used $hasEmail is true and value contains an email

public string $hasEmailError null
$hasUser public property

Check whether password contains the username

public boolean $hasUser true
$hasUserError public property

User-defined error message used when $hasUser is true and value contains the username

public string $hasUserError null
$haveIBeenPwned public property

Whether to check the online database of "Have I Been Pwned"

public boolean $haveIBeenPwned false
$haveIBeenPwnedError public property

User-defined error message used when password is found in Have I Been Pwned

$length public property

Specifies the length limit of the value to be validated. This can be specified in one of the

following forms:
  • an integer: the exact length that the value should be of;
  • an array of one element: the minimum length that the value should be of. For example, [8]. This will overwrite $min.
  • an array of two elements: the minimum and maximum lengths that the value should be of. For example, [8, 128]. This will overwrite both $min and $max.

See also:

  • $minError for the customized message for a too short string.
  • $maxError for the customized message for a too long string.
  • notEqual for the customized message for a string that does not match desired length.
public integer|array $length null
$lengthError public property

User-defined error message used when the length of the value is not equal to $length.

public string $lengthError null
$lower public property

Minimal number of lower case characters

public integer $lower 2
$lowerError public property

User-defined error message used when value contains less than $lower characters

public string $lowerError null
$max public property

Maximum length. If not set, it means no maximum length limit.

public integer $max null
$maxError public property

User-defined error message used when the length of the value is greater than $max.

public string $maxError null
$message public property

User-defined error message used when the value is not a string

public string $message null
$min public property

Minimum number of characters. If not set, defaults to 4.

public integer $min 4
$minError public property

User-defined error message used when the length of the value is smaller than $min.

public string $minError null
$preset public property

Preset - one of the preset constants. If this is not null, the preset parameters will override the validator level params

public string $preset null
$presetsSource public property

Presets configuration source file defaults to [[presets.php]] in the current directory

public string $presetsSource null
$repeat public property

Maximum number of same characters that can be repeated

public integer $repeat 2
$repeatError public property

User-defined error message used when the number of characters repeated exceeds $repeat.

public string $repeatError null
$special public property

Minimal number of special characters

public integer $special 2
$specialError public property

User-defined error message used when value contains more than $special characters

public string $specialError null
$strengthTarget public property

The target strength rule requirements that will be evaluated for displaying the strength meter

public array $strengthTarget = [
    'min' => 8'lower' => 3'upper' => 3'digit' => 3'special' => 3
]
$upper public property

Minimal number of upper case characters

public integer $upper 2
$upperError public property

User-defined error message used when value contains less than $upper characters

public string $upperError null
$userAttribute public property

The name of the username attribute

public string $userAttribute 'username'
$usernameValue public property

The value of the username to cross check for hasUser rule. This will override the userAttribute setting if this is set.

public string $usernameValue null

Method Details

applyPreset() protected method

Apply preset parameter if set

protected void applyPreset ( )
throws yii\base\InvalidConfigException

if $preset value is invalid.

checkParams() protected method

Validates the provided parameters for valid data type and the right threshold for 'max' chars.

protected void checkParams ( )
throws yii\base\InvalidConfigException

if validation is invalid

clientValidateAttribute() public method

Returns the JavaScript needed for performing client-side validation.

Calls getClientOptions() to generate options array for client-side validation.

You may override this method to return the JavaScript validation code if the validator can support client-side validation.

The following JavaScript variables are predefined and can be used in the validation code:

  • attribute: an object describing the the attribute being validated.
  • value: the value being validated.
  • messages: an array used to hold the validation error messages for the attribute.
  • deferred: an array used to hold deferred objects for asynchronous validation
  • $form: a jQuery object containing the form element

The attribute object contains the following properties:

  • id: a unique ID identifying the attribute (e.g. "loginform-username") in the form
  • name: attribute name or expression (e.g. "[0]content" for tabular input)
  • container: the jQuery selector of the container of the input field
  • input: the jQuery selector of the input field under the context of the form
  • error: the jQuery selector of the error tag under the context of the container
  • status: status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
public string|null clientValidateAttribute ( $model, $attribute, $view )
$model yii\base\Model

The data model being validated

$attribute string

The name of the attribute to be validated.

$view yii\web\View

The view object that is going to be used to render views or view files containing a model form with this validator applied.

return string|null

The client-side validation script. Null if the validator does not support client-side validation.

getRuleMessage() protected static method

Gets the localized rule message

protected static string getRuleMessage ( $rule )
$rule string

The rule to parse

init() public method

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

public void init ( )
throws ReflectionException
throws yii\base\InvalidConfigException
performValidation() protected method

The main password validation routine

protected array|null performValidation ( $params = [] )
$params array

Of model, attribute, and value

return array|null

The validated result

setRuleMessages() protected method

Sets the rule message for each rule

protected void setRuleMessages ( )
validateAttribute() public method

Validates a single attribute.

Child classes must implement this method to provide the actual validation logic.

public void validateAttribute ( $model, $attribute )
$model yii\base\Model

The data model to be validated

$attribute string

The name of the attribute to be validated.

validateValue() protected method

Validates a value.

A validator class can implement this method to support data validation out of the context of a data model.

protected array|null validateValue ( $value )
$value mixed

The data value to be validated.

return array|null

The error message and the array of parameters to be inserted into the error message. `php if (!$valid) {

return [$this->message, [
    'param1' => $this->param1,
    'formattedLimit' => Yii::$app->formatter->asShortSize($this->getSizeLimit()),
    'mimeTypes' => implode(', ', $this->mimeTypes),
    'param4' => 'etc...',
]];

}

return null; ` for this example message template can contain {param1}, {formattedLimit}, {mimeTypes}, {param4}

Null should be returned if the data is valid.

throws yii\base\NotSupportedException

if the validator does not supporting data validation without a model