Rules in YII2 Custom validation rule detailed _php instance

Source: Internet
Author: User

One of the strong parts of Yii2 is his form component, which is both convenient and secure. Some small partners feel with Yii for a period of time, well, in addition to TP "difficult to understand" seems to have nothing.

The leader arranges to make a registration function, this fellow brushes brush is also Baidu what what what good form style, is also Baidu what what what validate verification, really for this guy Pinch Khan.

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

Let's say the scene:

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

The requirement is: when the user chooses the value of a 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. Where a must be selected.

Let's take a look at how the rules are implemented with YII2.

First, add the following rule to the associated model

/**
* @inheritdoc
/Public Function rules () {return [[
' B '], ' requiredbyaspecial '],
];

Then in the model inside to implement 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 null.");
}

It means that when a is equal to 1 and the value of B is null, the value of the error message "B cannot be null."

The above is just a simple example that can be applied according to specific requirements.

The above is a small set up to introduce the YII2 rules to verify all the contents of the rule, I hope to 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.