Skip to content
PHP Ecosystem
Explore

DateValidator

API reference › yii › validators › DateValidator

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

DateValidator verifies if the attribute represents a date, time or datetime in a proper $format.

It can also parse internationalized dates in a specific $locale like e.g. 12 мая 2014 when $format is configured to use a time pattern in ICU format.

It is further possible to limit the date within a certain range using $min and $max.

Additional to validating the date it can also export the parsed timestamp as a machine readable format which can be configured using $timestampAttribute. For values that include time information (not date-only values) also the time zone will be adjusted. The time zone of the input value is assumed to be the one specified by the $timeZone property and the target timeZone will be UTC when $timestampAttributeFormat is null (exporting as UNIX timestamp) or $timestampAttributeTimeZone otherwise. If you want to avoid the time zone conversion, make sure that $timeZone and $timestampAttributeTimeZone are the same.

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
$defaultTimeZonestringThe default timezone used for parsing when no time parts are provided in the format. Default: 'UTC'. Available since 2.0.39.DateValidator
$enableClientValidationboolWhether to enable client-side validation for this validator. Default: true.Validator
$exceptarray|stringScenarios that the validator should not be applied to. Default: [].Validator
$formatstring|nullThe date format that the value being validated should follow. Default: null.DateValidator
$isEmptycallable|nullA PHP callable that replaces the default implementation of isEmpty(). Default: null.Validator
$localestring|nullThe locale ID that is used to localize the date parsing. Default: null.DateValidator
$maxint|string|nullUpper limit of the date. Default: null. Available since 2.0.4.DateValidator
$maxStringstring|nullUser friendly value of upper limit to display in the error message. Default: null. Available since 2.0.4.DateValidator
$messagestring|nullThe user-defined error message. Default: null.Validator
$minint|string|nullLower limit of the date. Default: null. Available since 2.0.4.DateValidator
$minStringstring|nullUser friendly value of lower limit to display in the error message. Default: null. Available since 2.0.4.DateValidator
$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
$strictDateFormatboolSet this parameter to true if you need strict date format validation (e.g. only such dates pass validation for the following format ‘yyyy-MM-dd’: ‘0011-03-25’, ‘2019-04-30’ etc. and not ‘18-05-15’, ‘2017-Mar-14’ etc. which pass validation if this parameter is set to false) Default: false. Available since 2.0.22.DateValidator
$timestampAttributestring|nullThe name of the attribute to receive the parsing result. Default: null.DateValidator
$timestampAttributeFormatstring|nullThe format to use when populating the $timestampAttribute. Default: null. Available since 2.0.4.DateValidator
$timestampAttributeTimeZonestringThe timezone to use when populating the $timestampAttribute with $timestampAttributeFormat. Default: 'UTC'. Available since 2.0.4.DateValidator
$timeZonestring|nullThe timezone to use for parsing date and time values. Default: null.DateValidator
$tooBigstringUser-defined error message used when the value is bigger than $max. Default: null. Available since 2.0.4.DateValidator
$tooSmallstringUser-defined error message used when the value is smaller than $min. Default: null. Available since 2.0.4.DateValidator
$typestringThe type of the validator. Default: self::TYPE_DATE. Available since 2.0.8.DateValidator
$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.DateValidator
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.DateValidator
validateAttributes()Validates the specified object.Validator
formatMessage() protectedFormats a mesage using the I18N, or simple strtr if \Yii::$app is not available.Validator
parseDateValue() protectedParses date string into UNIX timestamp.DateValidator
validateValue() protectedValidates a value.DateValidator
ConstantValueDescriptionDefined by
TYPE_DATE'date'Constant for specifying the validation $type as a date value, used for validation with intl short format. Available since 2.0.8.DateValidator
TYPE_DATETIME'datetime'Constant for specifying the validation $type as a datetime value, used for validation with intl short format. Available since 2.0.8.DateValidator
TYPE_TIME'time'Constant for specifying the validation $type as a time value, used for validation with intl short format. Available since 2.0.8.DateValidator
public string $defaultTimeZone = 'UTC'

The default timezone used for parsing when no time parts are provided in the format.

See $timestampAttributeTimeZone for more description.

Since

2.0.39

public string|null $format = null

The date format that the value being validated should follow.

This can be a date time pattern as described in the ICU manual.

Alternatively this can be a string prefixed with php: representing a format that can be recognized by the PHP Datetime class. Please refer to https://www.php.net/manual/en/datetime.createfromformat.php on supported formats.

If this property is not set, the default value will be obtained from Yii::$app->formatter->dateFormat, see Formatter::$dateFormat for details. Since version 2.0.8 the default value will be determined from different formats of the formatter class, dependent on the value of $type:

Here are some example values:

'MM/dd/yyyy' // date in ICU format
'php:m/d/Y' // the same date in PHP format
'MM/dd/yyyy HH:mm' // not only dates but also times can be validated

Note: the underlying date parsers being used vary dependent on the format. If you use the ICU format and the PHP intl extension is installed, the IntlDateFormatter is used to parse the input value. In all other cases the PHP DateTime class is used. The IntlDateFormatter has the advantage that it can parse international dates like 12. Mai 2015 or 12 мая 2014, while the PHP parser is limited to English only. The PHP parser however is more strict about the input format as it will not accept 12.05.05 for the format php:d.m.Y, but the IntlDateFormatter will accept it for the format dd.MM.yyyy. If you need to use the IntlDateFormatter you can avoid this problem by specifying a minimum date.

public string|null $locale = null

The locale ID that is used to localize the date parsing.

This is only effective when the PHP intl extension is installed. If not set, the locale of the formatter will be used. See also Formatter::$locale.

public int|string|null $max = null

Upper limit of the date.

Defaults to null, meaning no upper limit. This can be a unix timestamp or a string representing a date time value. If this property is a string, $format will be used to parse it.

Since

2.0.4

public string|null $maxString = null

User friendly value of upper limit to display in the error message.

If this property is null, the value of $max will be used (before parsing).

Since

2.0.4

public int|string|null $min = null

Lower limit of the date.

Defaults to null, meaning no lower limit. This can be a unix timestamp or a string representing a date time value. If this property is a string, $format will be used to parse it.

Since

2.0.4

public string|null $minString = null

User friendly value of lower limit to display in the error message.

If this property is null, the value of $min will be used (before parsing).

Since

2.0.4

public string|null $timestampAttribute = null

The name of the attribute to receive the parsing result.

When this property is not null and the validation is successful, the named attribute will receive the parsing result.

This can be the same attribute as the one being validated. If this is the case, the original value will be overwritten with the timestamp value after successful validation.

Note, that when using this property, the input value will be converted to a unix timestamp, which by definition is in default UTC time zone, so a conversion from the input time zone to the default one will be performed. If you want to change the default time zone, set the $defaultTimeZone property. When defining $timestampAttributeFormat you can further control the conversion by setting $timestampAttributeTimeZone to a different value than 'UTC'.

public string|null $timestampAttributeFormat = null

The format to use when populating the $timestampAttribute.

The format can be specified in the same way as for $format.

If not set, $timestampAttribute will receive a UNIX timestamp. If $timestampAttribute is not set, this property will be ignored.

Since

2.0.4

public string $timestampAttributeTimeZone = 'UTC'

The timezone to use when populating the $timestampAttribute with $timestampAttributeFormat.

Defaults to UTC.

This can be any value that may be passed to date_default_timezone_set() e.g. UTC, Europe/Berlin or America/Chicago. Refer to the php manual for available timezones.

If $timestampAttributeFormat is not set, this property will be ignored.

Since

2.0.4

public string|null $timeZone = null

The timezone to use for parsing date and time values.

This can be any value that may be passed to date_default_timezone_set() e.g. UTC, Europe/Berlin or America/Chicago. Refer to the php manual for available timezones. If this property is not set, Application::$timeZone will be used.

public string $type = self::TYPE_DATE

The type of the validator.

Indicates, whether a date, time or datetime value should be validated. This property influences the default value of $format and also sets the correct behavior when $format is one of the intl short formats, short, medium, long, or full.

This is only effective when the PHP intl extension is installed.

This property can be set to the following values:

  • TYPE_DATE - (default) for validating date values only, that means only values that do not include a time range are valid.
  • TYPE_DATETIME - for validating datetime values, that contain a date part as well as a time part.
  • TYPE_TIME - for validating time values, that contain no date information.

Since

2.0.8

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 parseDateValue(mixed $value): int|false

Parses date string into UNIX timestamp.

Parameters

ParameterTypeDescription
$valuemixedString representing date

Returns

int|false: A UNIX timestamp or false on failure.

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