首页 > 后端开发 > php教程 > yii2 model 验证规则rules 一条规则验证失败立即返回不继续验证其他字段

yii2 model 验证规则rules 一条规则验证失败立即返回不继续验证其他字段

ringa_lee
发布: 2023-03-01 06:06:02
原创
1405 人浏览过


yii2 model 验证规则rules 一条规则验证失败立即返回不继续验证其他字段

Mode::rules();

public function rules()
{
     [['username', 'password'], 'required'],
     ['age', 'required'],
     // ......

}
登录后复制
登录后复制

username 为空立即返回error ,不去验证password和age。同理age如果为空,也不会去验证其他字段

不知道yii2这块有没有这种配置?

回复内容:

yii2 model 验证规则rules 一条规则验证失败立即返回不继续验证其他字段

Mode::rules();

public function rules()
{
     [['username', 'password'], 'required'],
     ['age', 'required'],
     // ......

}
登录后复制
登录后复制

username 为空立即返回error ,不去验证password和age。同理age如果为空,也不会去验证其他字段

不知道yii2这块有没有这种配置?

验证完,再告诉你哪些字段没有通过验证。具体看代码。

/**
     * Performs the data validation.
     *
     * This method executes the validation rules applicable to the current [[scenario]].
     * The following criteria are used to determine whether a rule is currently applicable:
     *
     * - the rule must be associated with the attributes relevant to the current scenario;
     * - the rules must be effective for the current scenario.
     *
     * This method will call [[beforeValidate()]] and [[afterValidate()]] before and
     * after the actual validation, respectively. If [[beforeValidate()]] returns false,
     * the validation will be cancelled and [[afterValidate()]] will not be called.
     *
     * Errors found during the validation can be retrieved via [[getErrors()]],
     * [[getFirstErrors()]] and [[getFirstError()]].
     *
     * @param array $attributeNames list of attribute names that should be validated.
     * If this parameter is empty, it means any attribute listed in the applicable
     * validation rules should be validated.
     * @param boolean $clearErrors whether to call [[clearErrors()]] before performing validation
     * @return boolean whether the validation is successful without any error.
     * @throws InvalidParamException if the current scenario is unknown.
     */
    public function validate($attributeNames = null, $clearErrors = true)
    {
        if ($clearErrors) {
            $this->clearErrors();
        }

        if (!$this->beforeValidate()) {
            return false;
        }

        $scenarios = $this->scenarios();
        $scenario = $this->getScenario();
        if (!isset($scenarios[$scenario])) {
            throw new InvalidParamException("Unknown scenario: $scenario");
        }

        if ($attributeNames === null) {
            $attributeNames = $this->activeAttributes();
        }
        //注意这个foreach
        foreach ($this->getActiveValidators() as $validator) {
            $validator->validateAttributes($this, $attributeNames);
        }
        $this->afterValidate();

        return !$this->hasErrors();
    }
登录后复制
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板