Joke Collection Website - Public benefit messages - What are the custom validation rules for rules in yii2?

What are the custom validation rules for rules in yii2?

Conditions: ① The two fields are A and B2, and A has two values of 1 and 2 respectively.

The requirement is that when the value of A selected by the user is equal to 1, the value of B must be filled in. When the value of a is equal to 2, it doesn't matter if the value of b is not written. Among them, a is required.

First, add the following rules to its association model.

/**

* @inheritdoc

*/

Common function rule ()

{

Return [

[['B'],' requiredByASpecial'],

];

}

Then implement the requiredByASpecial method in the model.

/**

* custom authentication b

*/

Public function required by aspect ($ attribute, $params)

{

If ($ this->; A== 1)

{

If ($ this->; B=== ' ')

$ this-& gt; Add an error ($ attribute, "The value of b cannot be empty." );

}

}

When a is equal to 1 and the value of b is empty, the error message "The value of b cannot be empty" is returned.