One of the strengths of yii2 is its Form component, which is convenient and secure. This article introduces the rules custom verification rules in yii2. For more information, see its Form component. Some friends feel that they have been using yii for a while. well, it seems nothing except tp.
The leader arranged for a registration function. this guy is refreshing Baidu, what a good form style, and Baidu, and what a validate verification. he really sweated for this guy.
Of course, the point is to use ActiveForm to implement custom verification rules.
Let's talk about the scenario:
Condition: ① two fields are A and B, and A has two values: 1 and 2.
Requirement: when the value of user A is equal to 1, the value of B must be filled in. when the value of A is equal to 2, it does not matter if the value of B is not written. A is required.
Let's take a look at how to implement it using the Yii2 built-in rules.
Add the following rule to the associated model:
/*** @ Inheritdoc */public function rules () {return [['B'], 'requiredbyaspecial '],];}
Then implement the requiredByASpecial method in the model.
/*** Custom authentication B */public function requiredByASpecial ($ attribute, $ params) {if ($ this-> A = 1) {if ($ this-> B = '') $ this-> addError ($ attribute," the value of B cannot be blank. ");}}
If A is equal to 1 and B is null, the error message "the value of B cannot be blank" is returned ".
The above is just a simple example, which can be applied as needed.
The above section describes all the content of the yii2 rules verification rules that I will introduce to you. I hope this will help you!