# Yii 1 validators Yii has many built in [system validators](https://www.yiiframework.com/doc/api/1.1#system.validators). ## Yii Length validator ```php public function rules() { return [ ['code', 'length', 'is' => 13], ['last_name', 'length', 'min' => 2, 'tooShort' => 'Last name should be more than 2 chars'], ['office_id', 'length', 'max' => 100, 'tooLong' => 'Office Id cannot be more than 100'], ]; } ``` ## Yii 1 date validator See [date validation docs](https://www.yiiframework.com/doc/api/1.1/CDateValidator). Example of usage: ```php public function rules() { return [ ['published_on', 'date', 'dateFormat' => 'dd.MM.yyyy'], ]; } ``` ### How to create Yii custom dateValidator **Important:** Don't reinvent the weel, because Yii 1 has built-in [date](https://www.yiiframework.com/doc/api/1.1/CDateValidator) validator. If you want to write your own custom date validator you can create file at `protected/components/validators/` folder. This validator uses [DateTime::createFromFormat](https://www.php.net/manual/en/datetime.createfromformat.php) function, that returns `false` on failure. ```php class dateValidator extends CValidator { public $dateFormat = 'd.m.Y'; public $message = 'Invalid date format'; protected function validateAttribute($object, $attribute) { // Let another validator to check empty value if (empty($object->$attribute)) { return; } $dateString = $object->$attribute; $date = DateTime::createFromFormat($this->dateFormat, $dateString); if ($date === false) { $this->addError($object, $attribute, $this->message); } } } ``` To use this validator, just add this line to your `rules()` method: ```php public function rules() { return [ // By default 'dateFormat' param has value 'd.m.Y' ['published_on', 'dateValidator', 'dateFormat' => 'Y-m-d'], ]; } ```