Rumah >pembangunan bahagian belakang >tutorial php >yii2 model 验证规则rules 一条规则验证失败立即返回不继续验证其他字段
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(); }