PHP YII Framework Development tips for the model (models) in the rules of the custom validation rule, Yiirules
The rules section of Yii's models is a validation rule for some forms, which is useful for form validation, adding a form to the corresponding view (views), which is automatically validated by the rules of the form before it is submitted, and is only submitted after the restriction rules are valid. It can be very effective to ensure the security of forms and the validity of information. Or give you a specific explanation:
The following is a simple code for the Views section:
<?php $form = $this->beginwidget (' Cactiveform ', array ( ' id ' = = ' Tag-form ', ' enableajaxvalidation ' = >false,?> <?php echo $form->labelex ($model, ' tagname ');?> <?php Echo $form TextField ($model, ' tagname ', array (' Size ' =>20, ' maxlength ' =>32),?> <?php Echo $form->labelex ($ Model, ' Tagtype ');?> <?php echo $form->radiobuttonlist ($model, ' Tagtype ' array (1=> "normal tag",2=> " System default Tag "), Array (' separator ' = ', ' labeloptions ' =>array (' class ' = ' Tagtypelabel '));?> <?php echo $form->errorsummary ($model);?> <?php Echo chtml::submitbutton ($model->isnewrecord? ' Add ': ' Modify ');?>
Simple code for the Rules section of the Model (models):
Public Function Rules () { return array ( ' tagname,tagtype ', ' required '), array (' Tagtype ', ' Numerical ', ' integeronly ' =>true), array (' tagname ', ' length ', ' Max ' =>32), array (' tagname ', ' match ', ' Pattern ' = '/^[\x{4e00}-\x{9fa5}a-za-z0-9]+$/u ', ' message ' and ' = ' is illegal and must be kanji, letters or numbers! '), array (' tagname ', ' checktagname ', ' on ' = ' create,update '),//insert tag when checking if the tag array already exists (' TagID, tagname , Tagtype ', ' safe ', ' on ' = ' search '),
The system has these validation rules by default:
The alias of the Boolean:cbooleanvalidator to ensure that the value of the property is Cbooleanvalidator::truevalue or Cbooleanvalidator::falsevalue. The
Captcha:ccaptchavalidator alias ensures that the value of the attribute is equal to the verification code displayed by CAPTCHA. The alias of the
Compare:ccomparevalidator ensures that the value of the attribute is equal to another attribute or constant. The
Email:cemailvalidator alias ensures that the value of the attribute is a valid e-mail address. An alias for the
Default:cdefaultvaluevalidator that assigns a default value to the attribute. An alias for the
Exist:cexistvalidator that ensures that the property value exists in the specified data table field. The
File:cfilevalidator alias ensures that the attribute contains the name of an uploaded file. An alias for the
Filter:cfiltervalidator, using a Filter transformation property. The alias of the
In:crangevalidator ensures that the attribute appears in the list of values for a subscription. The alias of the
Length:cstringvalidator ensures that the length of the attribute is within the specified range. The alias of the
Match:cregularexpressionvalidator ensures that the attribute matches a regular expression. The alias of the
Numerical:cnumbervalidator ensures that the attribute is a valid number. The
Required:crequiredvalidator alias, which ensures that the attribute is not empty. The
Type:ctypevalidator alias, which ensures that the attribute is of the specified data type. The alias of the
Unique:cuniquevalidator ensures that the attribute is unique within the data table field. The
Url:curlvalidator alias ensures that the attribute is a valid path.
Basically, it's more comprehensive, but it's always enough, but there are times when some validation needs to be customized. As an example of the above code, we need to check the system before adding the tag, if there is no user to add. This will need to query the database before adding, to see if the tag already exists, here we need to customize a validation rule.
The key is two steps:
1, add code in the rules: Array (' tagname ', ' checktagname ', ' on ' = ' create,update '),//insert tag to check if the tag already exists
Note: I used ' on ' and ' create,update ' in it, so this validation rule is valid for create,update scenes
2. Add the validation function in the model (models):
Public Function Checktagname ($attribute, $params) { $oldtag = Tag::model ()->findbyattributes (Array (' tagname ' = > $this->tagname)); if ($oldtag->tagid > 0) { $this->adderror ($attribute, ' the tag already exists! ');
One of the things to note is:
(1) The parameters of the validation function must be ($attribute, $params) and not be missing any of them;
(2) $this->adderror ($attribute, ' the tag already exists! '); This is the error message that you want to output in the view.
It's that simple, with this method, the various desired rules of form validation can be customized.
The following is a description of Yii custom validation rules
The simplest way to define a validation rule is to define it internally using its model.
For example, you need to check if the user's password is secure enough.
Typically you will use the Cregularexpression method for validation, but for this guide we assume that this validation method does not exist.
First, add two constants to the model
Const WEAK = 0;
Const STRONG = 1; Then set in the rules method of the model:
/** * @return Array validation rules for model attributes. */public function Rules () { return Array ( array (' Password ', ' passwordstrength ', ' Strength ' =>self::strong) , );}
Make sure that the rule you write is not a rule that already exists, otherwise you will get an error.
What you need to do now is to create a method (that is, passwordstrength) in the model that is called the rule above.
/** * Check if the user password is strong enough * Check the password against the pattern requested * by the strength par Ameter * This was the ' passwordstrength ' validator as declared in rules (). */public function Passwordstrength ($attribute, $params) { if ($params [' strength '] = = = = Self::weak) $pattern = '/ ^ (? =.*[a-za-z0-9]). {5,}$/'; ElseIf ($params [' strength '] = = = Self::strong) $pattern = '/^ (? =.*\d (? =.*\d)) ' (? =.*[a-za-z] (? =.*[a-za-z])). { 5,}$/'; if (!preg_match ($pattern, $this, $attribute)) $this->adderror ($attribute, ' Your password is not strong Enough! ');}
The method you just created requires two parameters: * $attribute properties to validate * $params parameters that are customized in the rule
In the model's rules method we validate the password property, so the attribute value that needs to be validated in the validation rule should be password.
In the Rules method we also set the custom parameter strength, whose value will be placed in the $params array.
You will find that in the method we use the Cmodel::adderror ().
Adding an error accepts two parameters: the first parameter is the error message that appears when the wrong property name is displayed in the form, and the second parameter.
Complete approach: Inheriting the Cvalidator class
If you want to use rules in multiple models, the best way to inherit the Cvalidator class.
Inheriting this class you can use other features like Cactiveform:: $enableClientValidation (available after Yii 1.1.7 release).
To create a class file
The first thing to do is to create a class file. The best way to do this is when the class has the same file name and class name, and you can use Yii's lazy-load (lazy loading) feature.
Let's create a new folder under the app (application) extension (extensiions) directory (under the protected folder).
Name the directory: myvalidators
Then create the file: passwordstrength.php
Create our validation method in a file
Class Passwordstrength extends cvalidator{public $strength; Private $weak _pattern = '/^ (? =.*[a-za-z0-9]). {5,}$/'; Private $strong _pattern = '/^ (? =.*\d (? =.*\d)) (? =.*[a-za-z] (? =.*[a-za-z])). {5,}$/'; ...}
Create a property in the class that is the parameter that is used in the validation rule.
Cvalidator automatically populates these properties with parameters.
We have also created two other properties, which are regular expressions used by the Preg_match function.
Now we should rewrite the abstract method of the parent class (abstract methods) ValidateAttribute
/** * Validates the attribute of the object. * If There is an error, the error message is added to the object. * @param CModel $object The object being validated * @param string $attribute the attribute being validated */protected Fu Nction ValidateAttribute ($object, $attribute) { //Check the strength parameter used in the validation rule of our model if ($this->strength = = ' weak ') $pattern = $this->weak_pattern; ElseIf ($this->strength = = ' strong ') $pattern = $this->strong_pattern; Extract the attribute value from it ' s model object $value = $object $attribute; if (!preg_match ($pattern, $value)) { $this->adderror ($object, $attribute, ' Your password is too weak! '); }}
The above method I think there is no need to explain. Of course you can also use constants in the IF condition, which I recommend.
http://www.bkjia.com/PHPjc/1072188.html www.bkjia.com true http://www.bkjia.com/PHPjc/1072188.html techarticle PHP Yii Framework development of the small skill model (models) in the rules of the custom validation rule, Yiirules Yii models in the Rules section is some form of validation rules, for form validation is very useful, in ...