Backend Development 7 min read

Applying Yii2 Model Validation with Scenarios and Rules

This article explains how Yii2 uses validators and scenario configurations to perform comprehensive data validation in PHP models, illustrating the approach with a complete code example, detailed rule definitions, and guidance on using on/except, message, and scenarios methods.

Beike Product & Technology
Beike Product & Technology
Beike Product & Technology
Applying Yii2 Model Validation with Scenarios and Rules

In the interaction between a system and its data receivers, validating the format and content of incoming data is crucial; common cases include checking email, phone number, password, URLs, and IP addresses during user registration or profile updates.

Yii2 addresses these challenges through a meta‑programming approach called Validator , which tightly integrates with the Model layer to provide elegant, configurable validation rules.

The following example demonstrates a User model that defines public attributes such as $mobile , $email , $username , $password , $reg_ip , and $weibo_url . It declares a registration scenario constant and implements the rules() method, returning an array of rule specifications that cover required fields, conditional validation, format checks, uniqueness, length constraints, and pattern matching.

class User extends yii\base\Model
{
    public $mobile;
    public $email;
    public $username;
    public $password;
    public $reg_ip;
    public $weibo_url;
    const SCENARIO_REG = 'reg';
    public function rules()
    {
        return [
            // At least one of email or mobile must be provided
            [['email'], 'required', 'when' => function(self $model) {
                return !(new \yii\validators\RequiredValidator())->validate($model->mobile);
            }],
            // Validate email and IP formats
            ['email', 'email'],
            ['reg_ip', 'ip'],
            // Username must be unique during registration
            ['username', 'unique', 'on' => [self::SCENARIO_REG], 'message' => 'Your username is already taken, please choose another!'],
            // Username length between 8 and 16 characters
            ['username', 'string', 'length' => [8, 16]],
            // Password length between 8 and 20 characters
            ['password', 'string', 'min' => 8, 'max' => 20],
            // Username must start with a letter and contain only letters and numbers
            ['username', 'match', 'pattern' => '/[a-zA-Z]+[a-zA-Z0-9]*/'],
        ];
    }
}
$model = new User();
$model->setScenario('default');
$model->load($_POST, '');
if (!$model->validate()) {
    Yii::error($model->getErrors(), 'DATA_VALIDATION');
    // ... handle errors
}

The rules() method returns an array where each element defines the attributes to be validated, the validator (or a closure), and optional configuration such as on , except , or custom message values.

Scenarios allow the same model to apply different validation sets depending on the context (e.g., registration vs. profile update). By calling setScenario() and then validate() , Yii2 automatically selects the appropriate rules.

The on attribute specifies which scenarios enable a rule, while except lists scenarios where the rule is disabled; if both are present, on takes precedence.

The message attribute provides a custom error message when validation fails.

The scenarios() method returns a map of scenario names to their active attributes, derived from the rules unless overridden. The default scenario is default , which includes all rules without explicit on or except specifications.

In summary, Yii2’s model validation based on scenarios offers a concise, configurable way to enforce data integrity across different use cases, reducing duplication and improving maintainability.

BackendvalidationPHPModelscenarioYii2
Beike Product & Technology
Written by

Beike Product & Technology

As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.