Detailed description of custom verification rules for rules in yii2

Source: Internet
Author: User
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!

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.