Class kartik\password\StrengthValidator
Inheritance | kartik\password\StrengthValidator » yii\validators\Validator » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Uses Traits | kartik\base\TranslationTrait |
Available since version | 1.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
Property | Type | Description | Defined 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
Property | Type | Description | Defined By |
---|---|---|---|
$_msgCat | string | Translation message file category name for i18n. | kartik\base\TranslationTrait |
$_rules | array | The default rule settings | kartik\password\StrengthValidator |
Public Methods
Method | Description | Defined 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
Method | Description | Defined 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
Property Details
The default rule settings
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]
]
Whether to allow spaces in the input. Defaults to false
.
User-defined error message used when $allowSpaces is false
and spaces are found in input
The api for "Have I Been Pwned" check with trailing slash
See also https://haveibeenpwned.com/API/v3#SearchingPwnedPasswordsByRange.
Minimal number of numeric digit characters
User-defined error message used when value contains less than $digit characters
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.
Check whether password contains an email string
User-defined error message used $hasEmail is true and value contains an email
Check whether password contains the username
User-defined error message used when $hasUser is true and value contains the username
Whether to check the online database of "Have I Been Pwned"
User-defined error message used when password is found in Have I Been Pwned
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:
User-defined error message used when the length of the value is not equal to $length.
Minimal number of lower case characters
User-defined error message used when value contains less than $lower characters
Maximum length. If not set, it means no maximum length limit.
User-defined error message used when the length of the value is greater than $max.
User-defined error message used when the value is not a string
Minimum number of characters. If not set, defaults to 4.
User-defined error message used when the length of the value is smaller than $min.
Preset - one of the preset constants. If this is not null, the preset parameters will override the validator level params
Presets configuration source file defaults to [[presets.php]] in the current directory
Maximum number of same characters that can be repeated
User-defined error message used when the number of characters repeated exceeds $repeat.
Minimal number of special characters
User-defined error message used when value contains more than $special characters
The target strength rule requirements that will be evaluated for displaying the strength meter
'min' => 8, 'lower' => 3, 'upper' => 3, 'digit' => 3, 'special' => 3
]
Minimal number of upper case characters
User-defined error message used when value contains less than $upper characters
The name of the username attribute
The value of the username to cross check for hasUser
rule. This will override the userAttribute
setting if this is set.
Method Details
Apply preset parameter if set
protected void applyPreset ( ) | ||
throws | yii\base\InvalidConfigException | if $preset value is invalid. |
---|
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 |
---|
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 formname
: attribute name or expression (e.g. "[0]content" for tabular input)container
: the jQuery selector of the container of the input fieldinput
: the jQuery selector of the input field under the context of the formerror
: the jQuery selector of the error tag under the context of the containerstatus
: 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. |
---|
Gets the localized rule message
protected static string getRuleMessage ( $rule ) | ||
$rule | string | The rule to parse |
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 |
The main password validation routine
protected array|null performValidation ( $params = [] ) | ||
$params | array | Of model, attribute, and value |
return | array|null | The validated result |
---|
Sets the rule message for each rule
protected void setRuleMessages ( ) |
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. |
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.
} return null;
Null should be returned if the data is valid. |
---|---|---|
throws | yii\base\NotSupportedException | if the validator does not supporting data validation without a model |