我只是想知道是否有一种方法可以从您的rules
方法中运行验证函数,而您无需向该函数传递任何参数?
因此,通常您会传入属性的属性名称,但是说您知道要使用的属性,例如$this->foo and $this->bar
。
因此,普通的自定义内联验证器将像这样完成:
['country', 'validateCountry']
public function validateCountry($attribute, $params)
{
if (!in_array($this->$attribute, ['USA', 'Web'])) {
$this->addError($attribute, 'The country must be either "USA" or "Web".');
}
}
就像我目前正在这样做:
['username', 'regAvailable', 'params' => ['email' => 'email']],
public function regAvailable($attribute, $params) {
$username = $this->{$attribute};
$email = $this->{$params['email']};
}
当然可以。但是当我可以做的时候似乎有点矫seems过正:
public function regAvailable($attribute, $params) {
$username = $this->username;
$email = $this->email;
}
当然,我仍然可以用这种方式来做,但是然后我觉得通过将那些未使用的参数放在那儿,代码将不是很“干净”。我更喜欢这样:
public function regAvailable() {
$username = $this->username;
$email = $this->email;
}
反正有做这样的事情吗?如果是这样,怎么办?
当然可以。您可以避免将任何参数传递给自定义验证方法。例如:
public function regAvailable() {
if(!$this->hasErrors()){
if(strlen($this->email) < 10 && $this->email!='[email protected]' && $this->username!='admin'){
$this->addError('email','Invalid email!');
$this->addError('username','username must not be admin');
}
}
}
但是,请注意,如果您需要对多个字段执行一些验证,则使用这些参数将很有用。假设我们有9个字段需要验证上述功能之类的主题。因此,最好使用自$attribute
变量,因为它指向正在验证中的字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句