Skip to content

Commit 372cc09

Browse files
committed
add DateTimeValidator
1 parent 7b87ed7 commit 372cc09

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

DateTimeValidator.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?php
2+
3+
namespace nkovacs\datetimepicker;
4+
5+
use yii\validators\Validator;
6+
7+
/**
8+
* An improved version of Yii's DateValidator that supports parsing time as well.
9+
*/
10+
class DateTimeValidator extends \yii\validators\DateValidator
11+
{
12+
/**
13+
* @var string the type of value to accept: 'date', 'time' or 'datetime'.
14+
* This is only used when the format is ambiguous (i.e. one of the ICU short formats),
15+
* otherwise it is ignored, and the format dictates what is accepted.
16+
*/
17+
public $type = 'datetime';
18+
19+
/**
20+
* @inheritdoc
21+
*/
22+
public function init()
23+
{
24+
parent::init();
25+
// if $this->format is a short format,
26+
// convert it to a pattern, so that DateValidator will respect $this->type.
27+
$this->format = FormatConverter::convertIcuShortFormatToPattern($this->format, $this->type, $this->locale);
28+
}
29+
30+
/**
31+
* Replace built-in `date` validator and add `time` and `datetime` validator.
32+
*/
33+
public static function register()
34+
{
35+
Validator::$builtInValidators['date'] = [
36+
'class' => static::className(),
37+
'type' => 'date',
38+
];
39+
Validator::$builtInValidators['time'] = [
40+
'class' => static::className(),
41+
'type' => 'time',
42+
];
43+
Validator::$builtInValidators['datetime'] = static::className();
44+
}
45+
}

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,26 @@ The widget will load the moment locale file for `Yii::$app->language` if it can
6464
It will also use `Yii::$app->formatter->dateFormat`, `Yii::$app->formatter->timeFormat` or `Yii::$app->formatter->datetimeFormat` depending on `type`.
6565

6666
Both can be overriden using the `language` and `format` options.
67+
68+
Validators
69+
----------
70+
71+
The extension comes with an improved datetime validator. Yii's default DateValidator cannot handle
72+
time values with the default ICU 'medium' format. The validator adds a `type` option that specifies what
73+
kind of value should be accepted: `date`, `time` or `datetime`.
74+
75+
To register the validator, add the following line to your app config file:
76+
77+
```php
78+
\nkovacs\datetimepicker\DateTimeValidator::register();
79+
```
80+
81+
This replaces the built-in `date` validator and adds a `time` and `datetime` validator:
82+
83+
```php
84+
...
85+
['timestamp', 'datetime'],
86+
['time', 'time'],
87+
['date', 'date'],
88+
...
89+
```

0 commit comments

Comments
 (0)