Yii2 custom validation rules, yii2rules

Source: Internet
Author: User

Yii2 custom validation rules, yii2rules

Author: White Wolf Source: www. manks. top/article/yii2_custom_rules

The copyright of this article belongs to the author. You are welcome to repost this article, but you must keep this statement without the author's consent and provide the original article connection clearly on the article page. Otherwise, you will be entitled to pursue legal liability.

One of the strengths of yii2 is its Form component, which is convenient and secure. 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.

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.