Writing your own validators
Yii provides a good set of built-in form validators that cover the most typical developer needs and are highly configurable. However, in some cases, a developer may need to create a custom validator.
This recipe is a good example of creating a standalone validator that checks the number of words.
Getting ready
Create a new application by using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
How to do it...
- Create a standalone validator at
@app/components/WordsValidator.php
as follows:<?php namespace app\components; use yii\validators\Validator; class WordsValidator extends Validator { public $size = 50; public function validateValue($value){ if (str_word_count($value) > $this->size) { return ['The number of words must be less than {size}', ['size' => $this->size]]; } return false; } }
- Create an
Article...