Skip to content
PHP Ecosystem
Explore

CompareValidator

API reference › yii › validators › CompareValidator

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

CompareValidator compares the specified attribute value with another value.

The value being compared with can be another attribute value (specified via $compareAttribute) or a constant (specified via $compareValue). When both are specified, the latter takes precedence. If neither is specified, the attribute will be compared with another attribute whose name is by appending “_repeat” to the source attribute name.

CompareValidator supports different comparison operators, specified via the $operator property.

The default comparison function is based on string values, which means the values are compared byte by byte. When comparing numbers, make sure to set the $type to TYPE_NUMBER to enable numeric comparison.

PropertyTypeDescriptionDefined by
$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
$clientScriptarray|yii\validators\client\ClientValidatorScriptInterface|nullClient script class to use for client-side validation. Default: null.CompareValidator
$compareAttributestringThe name of the attribute to be compared with. Default: null.CompareValidator
$compareValuemixedThe constant value to be compared with or an anonymous function that returns the constant value. Default: null.CompareValidator
$enableClientValidationboolWhether to enable client-side validation for this validator. Default: true.Validator
$exceptarray|stringScenarios that the validator should not be applied to. Default: [].Validator
$isEmptycallable|nullA PHP callable that replaces the default implementation of isEmpty(). Default: null.Validator
$messagestring|nullThe user-defined error message. Default: null.CompareValidator
$onarray|stringScenarios that the validator can be applied to. Default: [].Validator
$operatorstringThe operator for comparison. Default: '=='.CompareValidator
$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
$typestringThe type of the values being compared. Default: self::TYPE_STRING.CompareValidator
$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.CompareValidator
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.CompareValidator
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.CompareValidator
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.CompareValidator
validateAttributes()Validates the specified object.Validator
compareValues() protectedCompares two values with the specified operator.CompareValidator
formatMessage() protectedFormats a mesage using the I18N, or simple strtr if \Yii::$app is not available.Validator
validateValue() protectedValidates a value.CompareValidator
ConstantValueDescriptionDefined by
TYPE_STRING'string'Constant for specifying the comparison $type by numeric values. Available since 2.0.11.CompareValidator
TYPE_NUMBER'number'Constant for specifying the comparison $type by numeric values. Available since 2.0.11.CompareValidator
public string $compareAttribute = null

The name of the attribute to be compared with.

When both this property and $compareValue are set, the latter takes precedence. If neither is set, it assumes the comparison is against another attribute whose name is formed by appending ‘_repeat’ to the attribute being validated. For example, if ‘password’ is being validated, then the attribute to be compared would be ‘password_repeat’.

public mixed $compareValue = null

The constant value to be compared with or an anonymous function that returns the constant value.

When both this property and $compareAttribute are set, this property takes precedence. The signature of the anonymous function should be as follows,

function($model, $attribute) {
// compute value to compare with
return $value;
}
public string|null $message = null

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
  • {compareValue}: the value or the attribute label to be compared with
  • {compareAttribute}: the label of the attribute to be compared with
  • {compareValueOrAttribute}: the value or the attribute label to be compared with
public string $operator = '=='

The operator for comparison.

The following operators are supported:

  • ==: check if two values are equal. The comparison is done is non-strict mode.
  • ===: check if two values are equal. The comparison is done is strict mode.
  • !=: check if two values are NOT equal. The comparison is done is non-strict mode.
  • !==: check if two values are NOT equal. The comparison is done is strict mode.
  • >: check if value being validated is greater than the value being compared with.
  • >=: check if value being validated is greater than or equal to the value being compared with.
  • <: check if value being validated is less than the value being compared with.
  • <=: check if value being validated is less than or equal to the value being compared with.

When you want to compare numbers, make sure to also set $type to number.

public string $type = self::TYPE_STRING

The type of the values being compared.

The follow types are supported:

  • string: the values are being compared as strings. No conversion will be done before comparison.
  • number: the values are being compared as numbers. String values will be converted into numbers before comparison.
public function clientValidateAttribute(mixed $model, mixed $attribute, mixed $view): string|null

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

Parameters

ParameterTypeDescription
$modelmixedThe data model being validated
$attributemixedThe name of the attribute to be validated.
$viewmixedThe 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.

public function getClientOptions(mixed $model, mixed $attribute): array

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.

Parameters

ParameterTypeDescription
$modelmixedThe model being validated
$attributemixedThe attribute name being validated

Returns

array: The client-side validation options

Since

2.0.11

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 compareValues(string $operator, string $type, mixed $value, mixed $compareValue): bool

Compares two values with the specified operator.

Parameters

ParameterTypeDescription
$operatorstringThe comparison operator
$typestringThe type of the values being compared
$valuemixedThe value being compared
$compareValuemixedAnother value being compared

Returns

bool: Whether the comparison using the specified operator is true.

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