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();
}