在我的表单模型中,我为这样定义的字段提供了一个自定义验证函数
class SignupForm extends Model
{
public function rules()
{
return [
['birth_date', 'checkDateFormat'],
// other rules
];
}
public function checkDateFormat($attribute, $params)
{
// no real check at the moment to be sure that the error is triggered
$this->addError($attribute, Yii::t('user', 'You entered an invalid date format.'));
}
}
当我按下提交按钮时,错误消息不会出现在表单视图中的字段下,而其他规则会出现,比如所需的电子邮件和密码。
我正在处理注册原生表单,所以为了确保这不是一个归档问题,我设置了规则
['username', 'checkDateFormat']
并删除了与用户名字段相关的所有其他规则,但消息也不会出现。
我尝试不将任何内容作为参数传递给checkDateFormat
,而是尝试将字段的名称显式传递给addError()
$this->addError('username', '....');
但是什么也没有出现。
设置自定义验证函数的正确方式是什么?
发布于 2015-08-15 01:28:53
尝试在空字段上强制执行验证
['birth_date', 'checkDateFormat', 'skipOnEmpty' => false, 'skipOnError' => false],
此外,请确保没有将id分配给视图中的birth_date
字段。
如果您的birth_date
具有id,则需要指定selectors
<?= $form->field($model, 'birth_date', ['selectors' => ['input' => '#myBirthDate']])->textInput(['id' => 'myBirthDate']) ?>
发布于 2016-08-12 15:31:01
要在yii 2中进行自定义验证,您可以在模型中编写自定义函数,并在规则中分配该函数。例如。我必须在password
字段中应用密码标准,然后我将在模型中这样写。
public function rules()
{
return [
['new_password','passwordCriteria'],
];
}
public function passwordCriteria()
{
if(!empty($this->new_password)){
if(strlen($this->new_password)<8){
$this->addError('new_password','Password must contains eight letters one digit and one character.');
}
else{
if(!preg_match('/[0-9]/',$this->new_password)){
$this->addError('new_password','Password must contain one digit.');
}
if(!preg_match('/[a-zA-Z]/', $this->new_password)){
$this->addError('new_password','Password must contain one character.');
}
}
}
}
发布于 2015-06-24 05:33:51
如果你是从类模型扩展的,你需要在某个地方触发$model->validate()
。
https://stackoverflow.com/questions/27805133
复制相似问题