Validator
API reference › yii › validators › Validator
22 subclasses
yii\captcha\CaptchaValidatorBooleanValidatorCompareValidatorDateValidatorDefaultValueValidatorEachValidatorEmailValidatorExistValidatorFileValidatorFilterValidatorInlineValidatorIpValidatorNumberValidatorRangeValidatorRegularExpressionValidatorRequiredValidatorSafeValidatorStringValidatorTrimValidatorUniqueValidatorUrlValidatoryii2\extensions\filepond\validator\EncodedFileValidator
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:
boolean:BooleanValidatorcaptcha:CaptchaValidatorcompare:CompareValidatordate:DateValidatordatetime:DateValidatortime:DateValidatordefault:DefaultValueValidatordouble:NumberValidatoreach:EachValidatoremail:EmailValidatorexist:ExistValidatorfile:FileValidatorfilter:FilterValidatorimage:ImageValidatorin:RangeValidatorinteger:NumberValidatormatch:RegularExpressionValidatorrequired:RequiredValidatorsafe:SafeValidatorstring:StringValidatortrim:TrimValidatorunique:UniqueValidatorurl:UrlValidatorip:IpValidator
For more details and usage information on Validator, see the guide article on validators.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$attributeNames read-only | array | Attribute names. | Validator |
$attributes | array| | Attributes to be validated by this validator. Default: []. | Validator |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$builtInValidators static | array | List of built-in validators (name => class or configuration) Default: ['boolean' => 'yii\. | Validator |
$enableClientValidation | bool | Whether to enable client-side validation for this validator. Default: true. | Validator |
$except | array| | Scenarios that the validator should not be applied to. Default: []. | Validator |
$isEmpty | callable| | A PHP callable that replaces the default implementation of isEmpty(). Default: null. | Validator |
$message | string| | The user-defined error message. Default: null. | Validator |
$on | array| | Scenarios that the validator can be applied to. Default: []. | Validator |
$skipOnEmpty | bool | Whether this validation rule should be skipped if the attribute value is null or an empty string. Default: true. | Validator |
$skipOnError | bool | Whether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Default: true. | Validator |
$validationAttributes read-only | array| | List of attribute names. | Validator |
$when | callable| | A PHP callable whose return value determines whether this validator should be applied. Default: null. | Validator |
$whenClient | string| | A JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: null. | Validator |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
addError() | Adds an error about the specified attribute to the model object. | Validator |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
className() static | Returns the fully qualified name of this class. | yii\ |
clientValidateAttribute() | Returns the JavaScript needed for performing client-side validation. | Validator |
createValidator() static | Creates a validator object. | Validator |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getAttributeNames() | Returns cleaned attribute names without the ! character at the beginning. | Validator |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getClientOptions() | Returns the client-side validation options. | Validator |
getFormattedClientMessage() | Returns the formatted validation message for client-side validation. | Validator |
getValidationAttributes() | Returns a list of attributes this validator applies to. | Validator |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the object. | Validator |
isActive() | Returns a value indicating whether the validator is active for the given scenario and attribute. | Validator |
isEmpty() | Checks if the given value is empty. | Validator |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
trigger() | Triggers an event. | yii\ |
validate() | Validates a given value. | Validator |
validateAttribute() | Validates a single attribute. | Validator |
validateAttributes() | Validates the specified object. | Validator |
formatMessage() protected | Formats a mesage using the I18N, or simple strtr if \ is not available. | Validator |
validateValue() protected | Validates a value. | Validator |
Property details
Section titled “Property details”$attributes
Section titled “$attributes ”public array|string $attributes = []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.
$enableClientValidation
Section titled “$enableClientValidation ”public bool $enableClientValidation = trueWhether 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
Section titled “$except ”public array|string $except = []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.
$isEmpty
Section titled “$isEmpty ”public callable|null $isEmpty = nullA 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.
$message
Section titled “$message ”public string|null $message = nullThe 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 array|string $on = []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.
$skipOnEmpty
Section titled “$skipOnEmpty ”public bool $skipOnEmpty = trueWhether this validation rule should be skipped if the attribute value is null or an empty string.
This property is used only when validating Model.
$skipOnError
Section titled “$skipOnError ”public bool $skipOnError = trueWhether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules.
Defaults to true.
$when
Section titled “$when ”public callable|null $when = nullA 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;}$whenClient
Section titled “$whenClient ”public string|null $whenClient = nullA 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';}Method details
Section titled “Method details”addError()
Section titled “addError() ”public function addError(yii\base\Model $model, string $attribute, string $message, array $params = []): mixedAdds an error about the specified attribute to the model object.
This is a helper method that performs message selection and internationalization.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | 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 |
Returns
mixed
clientValidateAttribute()
Section titled “clientValidateAttribute() ”public function clientValidateAttribute(yii\base\Model $model, string $attribute, yii\web\View $view): string|nullReturns 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
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The data model being validated |
$attribute | string | The name of the attribute to be validated. |
$view | yii\ | The view object that is going to be used to render views or view files containing a model form with this validator applied. |
Returns
string|null: The client-side validation script. Null if the validator does not support client-side validation.
See also
createValidator()
Section titled “createValidator() ”public static function createValidator(string|Closure $type, yii\base\Model $model, array|string $attributes, array $params = []): yii\validators\ValidatorCreates a validator object.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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\ | The data model to be validated. |
$attributes | array| | 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. |
Returns
Validator: The validator
getAttributeNames()
Section titled “getAttributeNames() ”public function getAttributeNames(): arrayReturns cleaned attribute names without the ! character at the beginning.
Returns
array: Attribute names.
Since
2.0.12
getClientOptions()
Section titled “getClientOptions() ”public function getClientOptions(yii\base\Model $model, string $attribute): arrayReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The model being validated |
$attribute | string | The attribute name being validated |
Returns
array: The client-side validation options
Since
2.0.11
getFormattedClientMessage()
Section titled “getFormattedClientMessage() ”public function getFormattedClientMessage(string $message, array<string, mixed> $params): stringReturns the formatted validation message for client-side validation.
This method can be overridden in subclasses to provide custom message formatting with validator-specific parameters.
Parameters
| Parameter | Type | Description |
|---|---|---|
$message | string | The message template to be formatted |
$params | array<string, | The parameters to be inserted into the message |
Returns
string: The formatted validation message
Since
22.0
getValidationAttributes()
Section titled “getValidationAttributes() ”public function getValidationAttributes(array|string|null $attributes = null): array|nullReturns a list of attributes this validator applies to.
Parameters
| Parameter | Type | Description |
|---|---|---|
$attributes | array| | The list of attributes to be validated. - If this is null, the result will be equal to getAttributeNames(). - If this is a string or an array, the intersection of getAttributeNames() and the specified attributes will be returned. |
Returns
array|null: List of attribute names.
Since
2.0.16
init()
Section titled “init() ”public function init(): mixedInitializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
Returns
mixed
isActive()
Section titled “isActive() ”public function isActive(string $scenario): boolReturns a value indicating whether the validator is active for the given scenario and attribute.
A validator is active if
- the validator’s
onproperty is empty, or - the validator’s
onproperty contains the specified scenario
Parameters
| Parameter | Type | Description |
|---|---|---|
$scenario | string | Scenario name |
Returns
bool: Whether the validator applies to the specified scenario.
isEmpty()
Section titled “isEmpty() ”public function isEmpty(mixed $value): boolChecks 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The value to be checked |
Returns
bool: Whether the value is empty
validate()
Section titled “validate() ”public function validate(mixed $value, string|null &$error = null): boolValidates a given value.
You may use this method to validate a value out of the context of a data model.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The data value to be validated. |
$error | string| | The error message to be returned, if the validation fails. |
Returns
bool: Whether the data is valid.
validateAttribute()
Section titled “validateAttribute() ”public function validateAttribute(yii\base\Model $model, string $attribute): mixedValidates a single attribute.
Child classes must implement this method to provide the actual validation logic.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The data model to be validated |
$attribute | string | The name of the attribute to be validated. |
Returns
mixed
validateAttributes()
Section titled “validateAttributes() ”public function validateAttributes(yii\base\Model $model, array|string|null $attributes = null): mixedValidates the specified object.
Parameters
| Parameter | Type | Description |
|---|---|---|
$model | yii\ | The data model being validated |
$attributes | array| | 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. |
Returns
mixed
formatMessage()
Section titled “formatMessage() ”protected function formatMessage(string $message, array $params): stringFormats a mesage using the I18N, or simple strtr if \Yii::$app is not available.
Parameters
| Parameter | Type | Description |
|---|---|---|
$message | string | |
$params | array |
Returns
string
Since
2.0.12
validateValue()
Section titled “validateValue() ”protected function validateValue(mixed $value): array|nullValidates a value.
A validator class can implement this method to support data validation out of the context of a data model.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | The data value to be validated. |
Returns
array|null: The error message and the array of parameters to be inserted into the error message. 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