Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the rules custom validation rules in the model in the development of PHP YII framework

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to understand the rules custom verification rules in the model of PHP YII framework development". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Here is the simple code for the views section:

Simple code for the rules part of the model (models):

Public function rules () {return array (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] + $/ message'= > 'tag is invalid) Must be Chinese characters, letters or numbers!') , array ('tagname',' checktagname', 'on'= >' create,update'), / / check whether the tag array already exists when inserting the TAG ('tagid, tagname, tagtype',' safe', 'on'= >' search'),);}

The system has these verification rules by default:

Boolean: alias for CBooleanValidator, make sure that the value of the property is CBooleanValidator::trueValue or CBooleanValidator::falseValue.

Captcha: an alias for CCaptchaValidator that ensures that the value of the property is equal to the CAPTCHA displayed by CAPTCHA.

Compare: an alias for CCompareValidator that ensures that the value of a property is equal to another property or constant.

Email: an alias for CEmailValidator that ensures that the value of the feature is a valid email address.

Default: an alias for CDefaultValueValidator that assigns a default value to the property.

Exist: an alias for CExistValidator to ensure that the property value exists in the specified datasheet field.

File: an alias for CFileValidator, which ensures that the feature contains the name of an uploaded file.

Filter: an alias for CFilterValidator, using a filter transformation property.

In: an alias for CRangeValidator that ensures that the feature appears in a subscribed list of values.

Length: an alias for CStringValidator that ensures that the length of the feature is within the specified range.

Match: an alias for CRegularExpressionValidator that ensures that the property matches a regular expression.

Numerical: an alias for CNumberValidator, which ensures that the feature is a valid number.

Required: an alias for CRequiredValidator, which ensures that the feature is not empty.

Type: an alias for CTypeValidator that ensures that the property is the specified data type.

Unique: an alias for CUniqueValidator that ensures that the feature is unique in the datasheet field.

Url: an alias for CUrlValidator, which ensures that the feature is a valid path.

Basically, it is quite comprehensive, and the general one is enough, but sometimes some validation needs to be customized. Taking the above code as an example, when we add a TAG, we need to check whether the TAG already exists on the system, and if so, do not allow the user to add it. Before adding this, you need to query the database to see if the TAG already exists, and here we need to customize a verification rule.

There are two key steps:

1. Add code to rules: array ('tagname',' checktagname', 'on'= >' create,update'), and / / check whether the tag already exists when you insert the tag

Note: I used 'on'= >' create,update', in it, so this validation rule takes effect for create,update scenarios

2. Add a 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,' the TAG already exists!');}}

What needs to be explained is:

(1) the argument to the validation function must be ($attribute,$params), and any one of them cannot be missing.

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

It's that simple. With this method, all the desired rules for form validation can be customized.

Now let's introduce the custom verification rules of Yii.

The easiest way to define a validation rule is within the model (model) that uses it.

For example, you need to check that the user's password is secure enough.

Normally you will use the CRegularExpression method for verification, but for the purposes of this guide, we assume that this method does not exist.

First add two constants to the model (model)

Const WEAK = 0

Const STRONG = 1; then set it in the rules method of the model (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 an existing rule, or you will report an error.

What you need to do now is to create a method in the model (model) named the rule you filled in above (that is, passwordStrength).

/ * * 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 enoughing');}

The method you just created requires two parameters: * the property that $attribute needs to validate * the parameter customized by $params in the rule

In the rules method of the model, we validate the password property, so the property 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 we use CModel::addError () in the method.

Add an error to accept two parameters: the first parameter is to display the wrong property name in the form, and the error message is displayed in the second parameter.

Complete method: inherit the CValidator class

If you want to use rules in multiple models (model), the best way is to inherit the CValidator class.

Inheriting this class you can use other features like CActiveForm::$enableClientValidation (available after Yii version 1.1.7).

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 file name is the same as the class name, and you can use yii's lazy loading (lazy loading) feature.

Let's create a new 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 a property in the class that is the parameter used in the validation rule.

CValidator automatically populates these properties based on the parameters.

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

Now we should override the parent class's abstract method (abstract method) 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 validation rules');}} "how to understand the rules custom validation rules in the model in the development of the PHP YII framework" is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report