Difference between #1 and #9 of
Create your own Validation Rule

Changes

Title unchanged

Create your own Validation Rule

Category unchanged

How-tos

Yii version unchanged

Tags unchanged

validator, validation rules, model validation, create validator

Content changed

Some times the core validation rules provided by Yii won't satisfy all your needs, so you'll need to create your very own validation rule. ##Easy approach: inside-model rule
 
================================
  

The easiest way to create a new validation rule is inside the model that is going to use it.
[...]
Usually you could achieve this result just by using the [CRegularExpressionValidator](http://www.yiiframework.com/doc/api/CRegularExpressionValidator) but for the sake of this guide let's pretend that validator does not exist.

first of all in your model
class you'll have to add two constants
 
 
```php 
const WEAK = 0;
 
const STRONG = 1;
 
```
 
 
 
then in your 
rules method you'll have to set the rule
[...]
* check if the user password is strong enough
* check the password against the pattern requested
* by the streng
hth parameter
* This is the 'passwordStrength' validator as declared in rules().
*/
[...]
In our rules method we used this rule on the password attribute, so the value of attribute inside our validation model will be **password**

In the rule we also setted an additional parameter named **streng
hth**
the value of that parameter will be inside the $params array
[...]
Add Error accepts two parameters: the first one is the name of the attribute that you want to display the error in your form, the second one is the actual error string you want to be displayed.

##Complete approach: extending the CValidator class
 
=================================================
  

If you need your custom validation rule in more then one model the best thing to do is extending the CValidator class.
[...]
);
}
```

 
 
##Links
 
* Russian version [The PHP Times](http://phptime.ru/blog/yii/27.html)
59 0
54 followers
Viewed: 272 651 times
Version: 1.1
Category: How-tos
Written by: nickcv
Last updated by: Gismo
Created on: Mar 31, 2011
Last updated: 11 years ago
Update Article

Revisions

View all history