Creating a custom client-side validation

In the Writing your own validators recipe, we created a standalone validator. In this recipe, we will modify a validator to create extra client-side validation, which also checks the number of words.

Getting ready

Create a new application by using the Composer package manger, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-startinstallation.html.

How to do it...

  1. Create @app/components/WordsValidator.php as follows:
    <?php namespace app\components; use yii\validators\Validator; class WordsValidator extends Validator { public $size = 50; public $message = 'The number of words must be less than {size}'; public function validateValue($value) { preg_match_all('/(\w+)/i', $value, $matches); ...

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.