Rules in yii2 the custom validation rule in detail _php instance

Source: Internet
Author: User
One of the great strengths of yii2 is his form component, which is both convenient and safe. Some small partners feel with Yii for a period of time, good, except than TP "difficult to understand" like nothing.

Leadership arrangements to engage in a registration function, this guy brushes brush is Baidu what what good form style, is Baidu what what what validate verification, really for this guy pinch sweat.

Of course, in front of the nonsense, our focus is to use ActiveForm, and then how to implement the custom validation rules.

First, let's say the scene:

Conditions: ①, two fields are A and B②, A has two values 1 and 2 respectively

The requirement is: when the user chooses a value equal to 1, the value of B must be filled in, when the value of a is equal to 2, the value of B does not matter. Where a must be selected.

Let's take a look at the rules that come with YII2.

First, add the following rule to the associated model.

 

Then in the model to implement the Requiredbyaspecial method can be

/*** Custom Validation b*/public function requiredbyaspecial ($attribute, $params) {if ($this->a== 1) {if ($this->b=== ") $this- >adderror ($attribute, "B's value cannot be empty.");}}

The above means that when a equals 1 and the value of B is null, the return error message "B's value cannot be null".

The above is just a simple example, can be applied according to the specific needs.

The above is a small series to introduce you to the YII2 rules of the entire content of the validation rule, I hope that everyone has help!

  • 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.