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){ ...
Get Yii2 Application Development Cookbook - Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.