Skip to content
PHP Ecosystem
Explore

ExistValidator

API reference › yii › validators › ExistValidator

classyii\validators\ExistValidator
ExtendsValidator » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Since2.0
Sourceframework/validators/ExistValidator.php

ExistValidator validates that the attribute value exists in a table.

ExistValidator checks if the value being validated can be found in the table column specified by the ActiveRecord class $targetClass and the attribute $targetAttribute. Since version 2.0.14 you can use more convenient attribute $targetRelation

This validator is often used to verify that a foreign key contains a value that can be found in the foreign table.

The following are examples of validation rules using this validator:

// a1 needs to exist
['a1', 'exist']
// a1 needs to exist, but its value will use a2 to check for the existence
['a1', 'exist', 'targetAttribute' => 'a2']
// a1 and a2 need to exist together, and they both will receive error message
[['a1', 'a2'], 'exist', 'targetAttribute' => ['a1', 'a2']]
// a1 and a2 need to exist together, only a1 will receive error message
['a1', 'exist', 'targetAttribute' => ['a1', 'a2']]
// a1 needs to exist by checking the existence of both a2 and a3 (using a1 value)
['a1', 'exist', 'targetAttribute' => ['a2', 'a1' => 'a3']]
// type_id needs to exist in the column "id" in the table defined in ProductType class
['type_id', 'exist', 'targetClass' => ProductType::class, 'targetAttribute' => ['type_id' => 'id']],
// the same as the previous, but using already defined relation "type"
['type_id', 'exist', 'targetRelation' => 'type'],
PropertyTypeDescriptionDefined by
$allowArrayboolWhether to allow array type attribute. Default: false.ExistValidator
$attributeNames read-onlyarrayAttribute names.Validator
$attributesarray|stringAttributes to be validated by this validator. Default: [].Validator
$behaviors read-onlyarray<yii\base\Behavior<static>>List of behaviors attached to this component.yii\base\Component
$builtInValidators staticarrayList of built-in validators (name => class or configuration) Default: ['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\TrimValidator', 'skipOnArray' => true], 'unique' => 'yii\validators\UniqueValidator', 'url' => 'yii\validators\UrlValidator', 'ip' => 'yii\validators\IpValidator'].Validator
$enableClientValidationboolWhether to enable client-side validation for this validator. Default: true.Validator
$exceptarray|stringScenarios that the validator should not be applied to. Default: [].Validator
$filterstring|array|ClosureAdditional filter to be applied to the DB query used to check the existence of the attribute value. Default: null.ExistValidator
$forceMasterDbboolWhether this validator is forced to always use master DB Default: true. Available since 2.0.14.ExistValidator
$isEmptycallable|nullA PHP callable that replaces the default implementation of isEmpty(). Default: null.Validator
$messagestring|nullThe user-defined error message. Default: null.Validator
$onarray|stringScenarios that the validator can be applied to. Default: [].Validator
$skipOnEmptyboolWhether this validation rule should be skipped if the attribute value is null or an empty string. Default: true.Validator
$skipOnErrorboolWhether this validation rule should be skipped if the attribute being validated already has some validation error according to some previous rules. Default: true.Validator
$targetAttributestring|array|nullThe name of the ActiveRecord attribute that should be used to validate the existence of the current attribute value. Default: null.ExistValidator
$targetAttributeJunctionstringAnd|or define how target attributes are related Default: 'and'. Available since 2.0.11.ExistValidator
$targetClassstring|nullThe name of the ActiveRecord class that should be used to validate the existence of the current attribute value. Default: null.ExistValidator
$targetRelationstringThe name of the relation that should be used to validate the existence of the current attribute value This param overwrites $targetClass and $targetAttribute Default: null. Available since 2.0.14.ExistValidator
$validationAttributes read-onlyarray|nullList of attribute names.Validator
$whencallable|nullA PHP callable whose return value determines whether this validator should be applied. Default: null.Validator
$whenClientstring|nullA JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: null.Validator
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__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
__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.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() staticReturns the fully qualified name of this class.yii\base\BaseObject
clientValidateAttribute()Returns the JavaScript needed for performing client-side validation.Validator
createValidator() staticCreates a validator object.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.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.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\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.ExistValidator
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\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.Validator
validateAttribute()Validates a single attribute.ExistValidator
validateAttributes()Validates the specified object.Validator
createQuery() protectedCreates a query instance with the given condition.ExistValidator
formatMessage() protectedFormats a mesage using the I18N, or simple strtr if \Yii::$app is not available.Validator
validateValue() protectedValidates a value.ExistValidator
public string|array|Closure $filter = null

Additional filter to be applied to the DB query used to check the existence of the attribute value.

This can be a string or an array representing the additional query condition (refer to Query::where() on the format of query condition), or an anonymous function with the signature function ($query), where $query is the Query object that you can modify in the function.

public string|array|null $targetAttribute = null

The name of the ActiveRecord attribute that should be used to validate the existence of the current attribute value.

If not set, it will use the name of the attribute currently being validated. You may use an array to validate the existence of multiple columns at the same time. The array key is the name of the attribute with the value to validate, the array value is the name of the database field to search.

public string|null $targetClass = null

The name of the ActiveRecord class that should be used to validate the existence of the current attribute value.

If not set, it will use the ActiveRecord class of the attribute being validated.

public function init(): mixed

Initializes the object.

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

Returns

mixed

public function validateAttribute(mixed $model, mixed $attribute): mixed

Validates a single attribute.

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

Parameters

ParameterTypeDescription
$modelmixedThe data model to be validated
$attributemixedThe name of the attribute to be validated.

Returns

mixed

protected function createQuery(string $targetClass, mixed $condition): yii\db\ActiveQueryInterface

Creates a query instance with the given condition.

Parameters

ParameterTypeDescription
$targetClassstringThe target AR class
$conditionmixedQuery condition

Returns

yii\db\ActiveQueryInterface: The query instance

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

Validates a value.

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

Parameters

ParameterTypeDescription
$valuemixedThe 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