# ExistValidator

> ExistValidator validates that the attribute value exists in a table.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [validators](/docs/api/yii/validators/index.md) › ExistValidator

| class | `yii\validators\ExistValidator` |
| --- | --- |
| Extends | [`Validator`](/docs/api/yii/validators/validator/index.md) » [`yii\base\Component`](/docs/api/yii/base/component/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Since | 2.0 |
| Source | [`framework/validators/ExistValidator.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/validators/ExistValidator.php#L50) |

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`](/docs/api/yii/validators/existvalidator/index.md#property-targetClass) and the attribute [`$targetAttribute`](/docs/api/yii/validators/existvalidator/index.md#property-targetAttribute).
Since version 2.0.14 you can use more convenient attribute [`$targetRelation`](/docs/api/yii/validators/existvalidator/index.md#property-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'],
```

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-allowArray"></span>`$allowArray` | `bool` | Whether to allow array type attribute. Default: `false`. | `ExistValidator` |
| <span id="property-attributeNames"></span>[`$attributeNames`](/docs/api/yii/validators/validator/index.md#property-attributeNames) read-only | `array` | Attribute names. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-attributes"></span>[`$attributes`](/docs/api/yii/validators/validator/index.md#property-attributes) | `array\|string` | Attributes to be validated by this validator. Default: `[]`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-behaviors"></span>[`$behaviors`](/docs/api/yii/base/component/index.md#property-behaviors) read-only | `array<`[`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md)`<static>>` | List of behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="property-builtInValidators"></span>[`$builtInValidators`](/docs/api/yii/validators/validator/index.md#property-builtInValidators) static | `array` | List 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`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-enableClientValidation"></span>[`$enableClientValidation`](/docs/api/yii/validators/validator/index.md#property-enableClientValidation) | `bool` | Whether to enable client-side validation for this validator. Default: `true`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-except"></span>[`$except`](/docs/api/yii/validators/validator/index.md#property-except) | `array\|string` | Scenarios that the validator should not be applied to. Default: `[]`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| [`$filter`](#property-filter) | `string\|array\|`[`Closure`](https://www.php.net/manual/en/class.closure.php) | Additional filter to be applied to the DB query used to check the existence of the attribute value. Default: `null`. | `ExistValidator` |
| <span id="property-forceMasterDb"></span>`$forceMasterDb` | `bool` | Whether this validator is forced to always use master DB Default: `true`. Available since 2.0.14. | `ExistValidator` |
| <span id="property-isEmpty"></span>[`$isEmpty`](/docs/api/yii/validators/validator/index.md#property-isEmpty) | `callable\|null` | A PHP callable that replaces the default implementation of [`isEmpty()`](/docs/api/yii/validators/validator/index.md#method-isEmpty). Default: `null`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-message"></span>[`$message`](/docs/api/yii/validators/validator/index.md#property-message) | `string\|null` | The user-defined error message. Default: `null`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-on"></span>[`$on`](/docs/api/yii/validators/validator/index.md#property-on) | `array\|string` | Scenarios that the validator can be applied to. Default: `[]`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-skipOnEmpty"></span>[`$skipOnEmpty`](/docs/api/yii/validators/validator/index.md#property-skipOnEmpty) | `bool` | Whether this validation rule should be skipped if the attribute value is null or an empty string. Default: `true`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-skipOnError"></span>[`$skipOnError`](/docs/api/yii/validators/validator/index.md#property-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`](/docs/api/yii/validators/validator/index.md) |
| [`$targetAttribute`](#property-targetAttribute) | `string\|array\|null` | The name of the ActiveRecord attribute that should be used to validate the existence of the current attribute value. Default: `null`. | `ExistValidator` |
| <span id="property-targetAttributeJunction"></span>`$targetAttributeJunction` | `string` | And\|or define how target attributes are related Default: `'and'`. Available since 2.0.11. | `ExistValidator` |
| [`$targetClass`](#property-targetClass) | `string\|null` | The name of the ActiveRecord class that should be used to validate the existence of the current attribute value. Default: `null`. | `ExistValidator` |
| <span id="property-targetRelation"></span>`$targetRelation` | `string` | The 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` |
| <span id="property-validationAttributes"></span>[`$validationAttributes`](/docs/api/yii/validators/validator/index.md#property-validationAttributes) read-only | `array\|null` | List of attribute names. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-when"></span>[`$when`](/docs/api/yii/validators/validator/index.md#property-when) | `callable\|null` | A PHP callable whose return value determines whether this validator should be applied. Default: `null`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="property-whenClient"></span>[`$whenClient`](/docs/api/yii/validators/validator/index.md#property-whenClient) | `string\|null` | A JavaScript function name whose return value determines whether this validator should be applied on the client-side. Default: `null`. | [`Validator`](/docs/api/yii/validators/validator/index.md) |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/component/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__clone"></span>[`__clone()`](/docs/api/yii/base/component/index.md#method-__clone) | This method is called after the object is created by cloning an existing one. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/component/index.md#method-__get) | Returns the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/component/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/component/index.md#method-__set) | Sets the value of a component property. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/component/index.md#method-__unset) | Sets a component property to be null. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-addError"></span>[`addError()`](/docs/api/yii/validators/validator/index.md#method-addError) | Adds an error about the specified attribute to the model object. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-attachBehavior"></span>[`attachBehavior()`](/docs/api/yii/base/component/index.md#method-attachBehavior) | Attaches a behavior to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-attachBehaviors"></span>[`attachBehaviors()`](/docs/api/yii/base/component/index.md#method-attachBehaviors) | Attaches a list of behaviors to the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-behaviors"></span>[`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) | Returns a list of behaviors that this component should behave as. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/component/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/component/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-clientValidateAttribute"></span>[`clientValidateAttribute()`](/docs/api/yii/validators/validator/index.md#method-clientValidateAttribute) | Returns the JavaScript needed for performing client-side validation. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-createValidator"></span>[`createValidator()`](/docs/api/yii/validators/validator/index.md#method-createValidator) static | Creates a validator object. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-detachBehavior"></span>[`detachBehavior()`](/docs/api/yii/base/component/index.md#method-detachBehavior) | Detaches a behavior from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-detachBehaviors"></span>[`detachBehaviors()`](/docs/api/yii/base/component/index.md#method-detachBehaviors) | Detaches all behaviors from the component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-ensureBehaviors"></span>[`ensureBehaviors()`](/docs/api/yii/base/component/index.md#method-ensureBehaviors) | Makes sure that the behaviors declared in [`behaviors()`](/docs/api/yii/base/component/index.md#method-behaviors) are attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getAttributeNames"></span>[`getAttributeNames()`](/docs/api/yii/validators/validator/index.md#method-getAttributeNames) | Returns cleaned attribute names without the `!` character at the beginning. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-getBehavior"></span>[`getBehavior()`](/docs/api/yii/base/component/index.md#method-getBehavior) | Returns the named behavior object. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getBehaviors"></span>[`getBehaviors()`](/docs/api/yii/base/component/index.md#method-getBehaviors) | Returns all behaviors attached to this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-getClientOptions"></span>[`getClientOptions()`](/docs/api/yii/validators/validator/index.md#method-getClientOptions) | Returns the client-side validation options. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-getFormattedClientMessage"></span>[`getFormattedClientMessage()`](/docs/api/yii/validators/validator/index.md#method-getFormattedClientMessage) | Returns the formatted validation message for client-side validation. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-getValidationAttributes"></span>[`getValidationAttributes()`](/docs/api/yii/validators/validator/index.md#method-getValidationAttributes) | Returns a list of attributes this validator applies to. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-hasEventHandlers"></span>[`hasEventHandlers()`](/docs/api/yii/base/component/index.md#method-hasEventHandlers) | Returns a value indicating whether there is any handler attached to the named event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/component/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/component/index.md#method-hasProperty) | Returns a value indicating whether a property is defined for this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| [`init()`](#method-init) | Initializes the object. | `ExistValidator` |
| <span id="method-isActive"></span>[`isActive()`](/docs/api/yii/validators/validator/index.md#method-isActive) | Returns a value indicating whether the validator is active for the given scenario and attribute. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-isEmpty"></span>[`isEmpty()`](/docs/api/yii/validators/validator/index.md#method-isEmpty) | Checks if the given value is empty. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| <span id="method-off"></span>[`off()`](/docs/api/yii/base/component/index.md#method-off) | Detaches an existing event handler from this component. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-on"></span>[`on()`](/docs/api/yii/base/component/index.md#method-on) | Attaches an event handler to an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-trigger"></span>[`trigger()`](/docs/api/yii/base/component/index.md#method-trigger) | Triggers an event. | [`yii\base\Component`](/docs/api/yii/base/component/index.md) |
| <span id="method-validate"></span>[`validate()`](/docs/api/yii/validators/validator/index.md#method-validate) | Validates a given value. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| [`validateAttribute()`](#method-validateAttribute) | Validates a single attribute. | `ExistValidator` |
| <span id="method-validateAttributes"></span>[`validateAttributes()`](/docs/api/yii/validators/validator/index.md#method-validateAttributes) | Validates the specified object. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| [`createQuery()`](#method-createQuery) protected | Creates a query instance with the given condition. | `ExistValidator` |
| <span id="method-formatMessage"></span>[`formatMessage()`](/docs/api/yii/validators/validator/index.md#method-formatMessage) protected | Formats a mesage using the I18N, or simple strtr if `\Yii::$app` is not available. | [`Validator`](/docs/api/yii/validators/validator/index.md) |
| [`validateValue()`](#method-validateValue) protected | Validates a value. | `ExistValidator` |

## Property details

### $filter <span id="property-filter"></span>

```php
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()`](/docs/api/yii/db/query/index.md#method-where)
on the format of query condition), or an anonymous function with the signature `function ($query)`, where `$query`
is the [Query](/docs/api/yii/db/query/index.md) object that you can modify in the function.

### $targetAttribute <span id="property-targetAttribute"></span>

```php
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.

### $targetClass <span id="property-targetClass"></span>

```php
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.

## Method details

### init() <span id="method-init"></span>

```php
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`

### validateAttribute() <span id="method-validateAttribute"></span>

```php
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**

| Parameter | Type | Description |
| --- | --- | --- |
| `$model` | `mixed` | The data model to be validated |
| `$attribute` | `mixed` | The name of the attribute to be validated. |

**Returns**

`mixed`

### createQuery() <span id="method-createQuery"></span>

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

Creates a query instance with the given condition.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$targetClass` | `string` | The target AR class |
| `$condition` | `mixed` | Query condition |

**Returns**

[`yii\db\ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md): The query instance

### validateValue() <span id="method-validateValue"></span>

```php
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**

| 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`](/docs/api/yii/base/notsupportedexception/index.md): if the validator does not supporting data validation without a model