相关疑难解决方法(0)

Yii2:如何为activeform使用自定义验证功能?

在我的表单模型中,我有一个自定义验证函数,用于以这种方式定义的字段

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.'));
    }
}
Run Code Online (Sandbox Code Playgroud)

当我按下提交按钮时,错误消息不会出现在表单视图中的字段下,而其他规则则显示所需的电子邮件和密码.

我正在处理注册本机表单,所以为了确保它不是一个存在的问题,我已经设置了规则

['username', 'checkDateFormat']
Run Code Online (Sandbox Code Playgroud)

并删除了与用户名字段相关的所有其他规则,但该消息也没有出现.

我已经尝试过什么都不作为参数checkDateFormat,我试图明确地传递该字段的名称addError()

$this->addError('username', '....');
Run Code Online (Sandbox Code Playgroud)

但没有出现.

设置自定义验证功能的正确方法是什么?

forms validation yii2

23
推荐指数
5
解决办法
6万
查看次数

标签 统计

forms ×1

validation ×1

yii2 ×1