Rules custom verification rules in model (models) with tips for PHPYII framework development

Source: Internet
Author: User
Tags valid email address
In models of yii, the rules section contains some form verification rules. it is helpful for form verification and adds a form in the corresponding views, before a form is submitted, the program will automatically come to the above rules for verification. The rules section in models of YII can be mentioned only after the rules are valid, it is very useful for form verification. a form is added to the corresponding views. before the form is submitted, the program automatically comes to the rules to verify the form, the submission can only be made after a valid restriction rule is applied. this effectively ensures form security and information validity. I 'd like to explain it to you in detail:

The following is a simple code for views:

<? 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 => "common TAG", 2 => "system default TAG "), array ('separator' => '', 'labeloptions' => array ('class' => 'tagpelabel ');?>

<? Php echo $ form-> errorSummary ($ model);?>

<? Php echo CHtml: submitButton ($ model-> isNewRecord? 'Add': 'modify');?>

<? Php $ this-> endWidget ();?>

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' =>' The tag is invalid, it must be a Chinese character, letter, or number! '), Array ('tagname', 'checktagname', 'on' => 'Create, update '), // check whether the TAG array ('tagid, tagname, tagtype', 'Safe ', 'on' => 'Search') exists During tag insertion '),);}

The system has these verification rules by default:

Boolean: the alias of CBooleanValidator. make sure that the attribute value is CBooleanValidator: trueValue or CBooleanValidator: falseValue.
Captcha: the alias of CCaptchaValidator to ensure that the feature value is equal to the verification code displayed by CAPTCHA.
Compare: the alias of CCompareValidator, ensuring that the value of a feature is equal to another feature or constant.
Email: the alias of CEmailValidator, which ensures that the feature value is a valid email address.
Default: the alias of cdefavaluvaluevalidator, which assigns a default value for the feature.
Exist: the alias of CExistValidator to ensure that the attribute value exists in the specified data table field.
File: the alias of CFileValidator, which ensures that the feature contains the name of an uploaded file.
Filter: the alias of CFilterValidator. a filter conversion attribute is used.
In: the alias of CRangeValidator, ensuring that the feature appears in a reserved value list.
Length: the alias of CStringValidator to ensure that the length of the feature is within the specified range.
Match: the alias of CRegularExpressionValidator to ensure that the feature matches a regular expression.
Numerical: the alias of CNumberValidator, which ensures that the feature is a valid number.
Required: the alias of CRequiredValidator. This ensures that the feature is not empty.
Type: the alias of CTypeValidator, which ensures that the feature is of the specified data type.
Unique: The alias of CUniqueValidator, which ensures that the feature is unique in the data table fields.
Url: the alias of CUrlValidator, which ensures that the feature is a valid path.

Basically, it is comprehensive and generally enough, but sometimes some verification needs to be customized. Take the preceding code as an example. when adding a TAG, we need to check whether the TAG already exists in the system. if the TAG exists, the user is not allowed to add it. This requires you to query the database before adding the TAG to check whether the TAG already exists. here we need to customize a Validation rule.

There are two key steps:

1. add code to rules: array ('tagname', 'checktagname', 'on' => 'Create, update '), // when inserting a TAG, check whether the tag already exists.

Note: I used 'on' => 'Create, Update' in it, so this verification rule takes effect for the create and update scenarios.

2. add the verification function to the model (models:

Public function checktagname ($ attribute, $ params) {$ oldtag = Tag: model ()-> findByAttributes (array ('tagname' => $ this-> tagname )); if ($ oldtag-> tagid> 0) {$ this-> addError ($ attribute, 'this TAG already exists! ');}}

Note the following:

(1) the parameter of the verification function must be ($ attribute, $ params), and no one of them must be missing;

(2) $ this-> addError ($ attribute, 'this TAG already exists! '); This is the error message you want to output in the view.

With this method, all the desired rules for form verification can be customized.

The following describes the Yii custom verification rules.

The simplest way to define a verification rule is to define it within the model that uses it.

For example, you need to check whether your password is safe enough.

In general, you will use the CRegularExpression method for verification, but for this guide, we assume that this verification method does not exist.

First, add two constants to the model.

Const WEAK = 0;
Const STRONG = 1; then set it in the model's rules method:

/** * @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 an existing rule. Otherwise, an error will be reported.

Now, you need to create a method (passwordStrength) named as the rule entered above in the model ).

/** * check if the user password is strong enough * check the password against the pattern requested * by the strength parameter * This is 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 just created requires two parameters: * $ attribute to be verified * $ params custom parameters in the rule

In the model's rules method, the password attribute is verified. Therefore, the attribute value to be verified in the verification rules should be password.

In the rules method, we also set the custom parameter strength. its value will be placed in the $ params array.

You will find that CModel: addError () is used in the method ().

Two parameters are accepted for adding an error: The first parameter displays the incorrect attribute name in the form and the second parameter displays the error message.

Complete Method: inherit the CValidator class

If you want to use rules in multiple models, the best method inherits the CValidator class.

To inherit from this class, you can use other functions similar to CActiveForm: $ enableClientValidation (available after Yii 1.1.7.

Create a class file

The first thing to do is to create a class file. when the best method is, the class file name is the same as the class name. you can use the lazy loading function of yii.

Let's create a folder under the extensiions Directory of the application (under the protected folder.

Name the directory MyValidators

Then create the file passwordStrength. php.

Create our verification method in the 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 an attribute in the class, which is a parameter used in the validation rule.

CValidator automatically fills in these attributes based on parameters.

We have also created two other attributes, which are the regular expressions used by the preg_match function.

Now we should rewrite the abstract method of the parent class (validateAttribute ).

/** * Validates the attribute of the object. * If there is any error, the error message is added to the object. * @param CModel $object the object being validated * @param string $attribute the attribute being validated */protected function 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 does not need to be explained. of course, you can also use constants in the if condition. I recommend that you use constants.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.