Class yii\validators\Validator

Inheritanceyii\validators\Validator » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Subclassesyii\captcha\CaptchaValidator, yii\mongodb\validators\MongoDateValidator, yii\mongodb\validators\MongoIdValidator, yii\validators\BooleanValidator, yii\validators\CompareValidator, yii\validators\DateValidator, yii\validators\DefaultValueValidator, yii\validators\EachValidator, yii\validators\EmailValidator, yii\validators\ExistValidator, yii\validators\FileValidator, yii\validators\FilterValidator, yii\validators\ImageValidator, yii\validators\InlineValidator, yii\validators\IpValidator, yii\validators\NumberValidator, yii\validators\RangeValidator, yii\validators\RegularExpressionValidator, yii\validators\RequiredValidator, yii\validators\SafeValidator, yii\validators\StringValidator, yii\validators\UniqueValidator, yii\validators\UrlValidator
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/validators/Validator.php

Validator is the base class for all validators.

Child classes should override the validateValue() and/or validateAttribute() methods to provide the actual logic of performing data validation. Child classes may also override clientValidateAttribute() to provide client-side validation support.

Validator declares a set of built-in validators which can be referenced using short names. They are listed as follows:

For more details and usage information on Validator, see the guide article on validators.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$attributes array|string Attributes to be validated by this validator. yii\validators\Validator
$builtInValidators array List of built-in validators (name => class or configuration) yii\validators\Validator
$enableClientValidation boolean Whether to enable client-side validation for this validator. yii\validators\Validator
$except array|string Scenarios that the validator should not be applied to. yii\validators\Validator
$isEmpty callable A PHP callable that replaces the default implementation of isEmpty(). yii\validators\Validator
$message string The user-defined error message. yii\validators\Validator
$on array|string Scenarios that the validator can be applied to. yii\validators\Validator
$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
$when callable A PHP callable whose return value determines whether this validator should be applied. yii\validators\Validator
$whenClient string A JavaScript function name whose return value determines whether this validator should be applied on the client-side. yii\validators\Validator

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. yii\validators\Validator
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() {@inheritdoc} yii\validators\Validator
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. yii\validators\Validator
validateAttributes() Validates the specified object. yii\validators\Validator

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
formatMessage() Formats a mesage using the I18N, or simple strtr if \Yii::$app is not available. yii\validators\Validator
validateValue() Validates a value. yii\validators\Validator

Property Details

$attributes public property

Attributes to be validated by this validator. For multiple attributes, please specify them as an array; for single attribute, you may use either a string or an array.

public array|string $attributes = []
$builtInValidators public static property

List of built-in validators (name => class or configuration)

public static array $builtInValidators = ['boolean' => 'yii\validators\BooleanValidator''captcha' => 'yii\captcha\CaptchaValidator''compare' => 'yii\validators\CompareValidator''date' => 'yii\validators\DateValidator''datetime' => ['class' => 'yii\validators\DateValidator''type' => \yii\validators\DateValidator::TYPE_DATETIME], 'time' => ['class' => 'yii\validators\DateValidator''type' => \yii\validators\DateValidator::TYPE_TIME], 'default' => 'yii\validators\DefaultValueValidator''double' => 'yii\validators\NumberValidator''each' => 'yii\validators\EachValidator''email' => 'yii\validators\EmailValidator''exist' => 'yii\validators\ExistValidator''file' => 'yii\validators\FileValidator''filter' => 'yii\validators\FilterValidator''image' => 'yii\validators\ImageValidator''in' => 'yii\validators\RangeValidator''integer' => ['class' => 'yii\validators\NumberValidator''integerOnly' => true], 'match' => 'yii\validators\RegularExpressionValidator''number' => 'yii\validators\NumberValidator''required' => 'yii\validators\RequiredValidator''safe' => 'yii\validators\SafeValidator''string' => 'yii\validators\StringValidator''trim' => ['class' => 'yii\validators\FilterValidator''filter' => 'trim''skipOnArray' => true], 'unique' => 'yii\validators\UniqueValidator''url' => 'yii\validators\UrlValidator''ip' => 'yii\validators\IpValidator']
$enableClientValidation public property

Whether to enable client-side validation for this validator. The actual client-side validation is done via the JavaScript code returned by clientValidateAttribute(). If that method returns null, even if this property is true, no client-side validation will be done by this validator.

$except public property

Scenarios that the validator should not be applied to. For multiple scenarios, please specify them as an array; for single scenario, you may use either a string or an array.

public array|string $except = []
$isEmpty public property

A PHP callable that replaces the default implementation of isEmpty(). If not set, isEmpty() will be used to check if a value is empty. The signature of the callable should be function ($value) which returns a boolean indicating whether the value is empty.

public callable $isEmpty null
$message public property

The user-defined error message. It may contain the following placeholders which will be replaced accordingly by the validator:

  • {attribute}: the label of the attribute being validated
  • {value}: the value of the attribute being validated

Note that some validators may introduce other properties for error messages used when specific validation conditions are not met. Please refer to individual class API documentation for details about these properties. By convention, this property represents the primary error message used when the most important validation condition is not met.

public string $message null
$on public property

Scenarios that the validator can be applied to. For multiple scenarios, please specify them as an array; for single scenario, you may use either a string or an array.

public array|string $on = []
$skipOnEmpty public property

Whether this validation rule should be skipped if the attribute value is null or an empty string. This property is used only when validating \yii\validators\yii\base\Model.

public boolean $skipOnEmpty true
$skipOnError public property

Whether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Defaults to true.

public boolean $skipOnError true
$when public property

A PHP callable whose return value determines whether this validator should be applied. The signature of the callable should be function ($model, $attribute), where $model and $attribute refer to the model and the attribute currently being validated. The callable should return a boolean value.

This property is mainly provided to support conditional validation on the server-side. If this property is not set, this validator will be always applied on the server-side.

The following example will enable the validator only when the country currently selected is USA:

function ($model) {
    return $model->country == Country::USA;
}

See also $whenClient.

public callable $when null
$whenClient public property

A JavaScript function name whose return value determines whether this validator should be applied on the client-side. The signature of the function should be function (attribute, value), where attribute is an object describing the attribute being validated (see clientValidateAttribute()) and value the current value of the attribute.

This property is mainly provided to support conditional validation on the client-side. If this property is not set, this validator will be always applied on the client-side.

The following example will enable the validator only when the country currently selected is USA:

function (attribute, value) {
    return $('#country').val() === 'USA';
}

See also $when.

public string $whenClient null

Method Details

addError() public method

Adds an error about the specified attribute to the model object.

This is a helper method that performs message selection and internationalization.

public void addError ( $model, $attribute, $message, $params = [] )
$model yii\base\Model

The data model being validated

$attribute string

The attribute being validated

$message string

The error message

$params array

Values for the placeholders in the error message

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

See also:

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.

createValidator() public static method

Creates a validator object.

public static yii\validators\Validator createValidator ( $type, $model, $attributes, $params = [] )
$type string|Closure

The validator type. This can be either:

  • a built-in validator name listed in $builtInValidators;
  • a method name of the model class;
  • an anonymous function;
  • a validator class name.
$model yii\base\Model

The data model to be validated.

$attributes array|string

List of attributes to be validated. This can be either an array of the attribute names or a string of comma-separated attribute names.

$params array

Initial values to be applied to the validator properties.

return yii\validators\Validator

The validator

formatMessage() protected method (available since version 2.0.12)

Formats a mesage using the I18N, or simple strtr if \Yii::$app is not available.

protected string formatMessage ( $message, $params )
$message string
$params array
getAttributeNames() public method (available since version 2.0.12)

Returns cleaned attribute names without the ! character at the beginning.

public array getAttributeNames ( )
return array

Attribute names.

getClientOptions() public method (available since version 2.0.11)

Returns the client-side validation options.

This method is usually called from clientValidateAttribute(). You may override this method to modify options that will be passed to the client-side validation.

public array getClientOptions ( $model, $attribute )
$model yii\base\Model

The model being validated

$attribute string

The attribute name being validated

return array

The client-side validation options

getValidationAttributes() public method (available since version 2.0.16)

Returns a list of attributes this validator applies to.

public array getValidationAttributes ( $attributes null )
$attributes array|string|null

The list of attributes to be validated.

return array

List of attribute names.

init() public method

{@inheritdoc}

public void init ( )
isActive() public method

Returns a value indicating whether the validator is active for the given scenario and attribute.

A validator is active if

  • the validator's on property is empty, or
  • the validator's on property contains the specified scenario
public boolean isActive ( $scenario )
$scenario string

Scenario name

return boolean

Whether the validator applies to the specified scenario.

isEmpty() public method

Checks if the given value is empty.

A value is considered empty if it is null, an empty array, or an empty string. Note that this method is different from PHP empty(). It will return false when the value is 0.

public boolean isEmpty ( $value )
$value mixed

The value to be checked

return boolean

Whether the value is empty

validate() public method

Validates a given value.

You may use this method to validate a value out of the context of a data model.

public boolean validate ( $value, &$error null )
$value mixed

The data value to be validated.

$error string

The error message to be returned, if the validation fails.

return boolean

Whether the data is valid.

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.

validateAttributes() public method

Validates the specified object.

public void validateAttributes ( $model, $attributes null )
$model yii\base\Model

The data model being validated

$attributes array|string|null

The list of attributes to be validated. Note that if an attribute is not associated with the validator - it will be ignored. If this parameter is null, every attribute listed in $attributes will 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