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...
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); if (count($matches[0]) > $this->size) { return [$this->message, ['size' => $this->size]]; } } public function clientValidateAttribute($model, $attribute, $view) ...