DateValidator
API reference › yii › validators › DateValidator
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.
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 |
$defaultTimeZone | string | The default timezone used for parsing when no time parts are provided in the format. Default: 'UTC'. Available since 2.0.39. | DateValidator |
$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 |
$format | string| | The date format that the value being validated should follow. Default: null. | DateValidator |
$isEmpty | callable| | A PHP callable that replaces the default implementation of isEmpty(). Default: null. | Validator |
$locale | string| | The locale ID that is used to localize the date parsing. Default: null. | DateValidator |
$max | int| | Upper limit of the date. Default: null. Available since 2.0.4. | DateValidator |
$maxString | string| | User friendly value of upper limit to display in the error message. Default: null. Available since 2.0.4. | DateValidator |
$message | string| | The user-defined error message. Default: null. | Validator |
$min | int| | Lower limit of the date. Default: null. Available since 2.0.4. | DateValidator |
$minString | string| | User friendly value of lower limit to display in the error message. Default: null. Available since 2.0.4. | DateValidator |
$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 |
$strictDateFormat | bool | Set 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 |
$timestampAttribute | string| | The name of the attribute to receive the parsing result. Default: null. | DateValidator |
$timestampAttributeFormat | string| | The format to use when populating the $timestampAttribute. Default: null. Available since 2.0.4. | DateValidator |
$timestampAttributeTimeZone | string | The timezone to use when populating the $timestampAttribute with $timestampAttributeFormat. Default: 'UTC'. Available since 2.0.4. | DateValidator |
$timeZone | string| | The timezone to use for parsing date and time values. Default: null. | DateValidator |
$tooBig | string | User-defined error message used when the value is bigger than $max. Default: null. Available since 2.0.4. | DateValidator |
$tooSmall | string | User-defined error message used when the value is smaller than $min. Default: null. Available since 2.0.4. | DateValidator |
$type | string | The type of the validator. Default: self::TYPE_DATE. Available since 2.0.8. | DateValidator |
$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. | 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\ |
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. | DateValidator |
validateAttributes() | Validates the specified object. | Validator |
formatMessage() protected | Formats a mesage using the I18N, or simple strtr if \ is not available. | Validator |
parseDateValue() protected | Parses date string into UNIX timestamp. | DateValidator |
validateValue() protected | Validates a value. | DateValidator |
Constants
Section titled “Constants”| Constant | Value | Description | Defined 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 |
Property details
Section titled “Property details”$defaultTimeZone
Section titled “$defaultTimeZone ”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
$format
Section titled “$format ”public string|null $format = nullThe 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:
- if type is
TYPE_DATE, the default value will be taken fromFormatter::$dateFormat, - if type is
TYPE_DATETIME, it will be taken fromFormatter::$datetimeFormat, - and if type is
TYPE_TIME, it will beFormatter::$timeFormat.
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 validatedNote: 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.
$locale
Section titled “$locale ”public string|null $locale = nullThe 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 = nullUpper 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
$maxString
Section titled “$maxString ”public string|null $maxString = nullUser 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 = nullLower 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
$minString
Section titled “$minString ”public string|null $minString = nullUser 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
$timestampAttribute
Section titled “$timestampAttribute ”public string|null $timestampAttribute = nullThe 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'.
$timestampAttributeFormat
Section titled “$timestampAttributeFormat ”public string|null $timestampAttributeFormat = nullThe 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
$timestampAttributeTimeZone
Section titled “$timestampAttributeTimeZone ”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
$timeZone
Section titled “$timeZone ”public string|null $timeZone = nullThe 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.
$type
Section titled “$type ”public string $type = self::TYPE_DATEThe 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
Method details
Section titled “Method details”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
validateAttribute()
Section titled “validateAttribute() ”public function validateAttribute(mixed $model, mixed $attribute): mixedValidates 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
parseDateValue()
Section titled “parseDateValue() ”protected function parseDateValue(mixed $value): int|falseParses date string into UNIX timestamp.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | mixed | String representing date |
Returns
int|false: A UNIX timestamp or false on failure.
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