首頁 >後端開發 >php教程 >yii2 model 驗證規則rules 一條規則驗證失敗立即返回不繼續驗證其他字段

yii2 model 驗證規則rules 一條規則驗證失敗立即返回不繼續驗證其他字段

ringa_lee
ringa_lee原創
2018-05-10 14:35:211397瀏覽


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 為空立即返回words ,並驗證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();
    }
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn