Yii2:如何为 activeform 使用自定义验证功能? [英] Yii2: how to use custom validation function for activeform?

查看:22
本文介绍了Yii2:如何为 activeform 使用自定义验证功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my form's model, I have a custom validation function for a field defined in this way

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.'));
    }
}

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

The error message doesn't appear under the field in the form view when I push the submit button, while other rules like the required email and password appear.

我正在处理 Signup 原生表单,所以为了确保这不是一个已归档的问题,我已经设置了规则

I'm working on the Signup native form, so to be sure that it is not a filed problem, I've set the rule

['username', 'checkDateFormat']

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

and removed all the other rules related to the username field, but the message doesn't appear either for it.

我尝试不将任何内容作为参数传递给 checkDateFormat,我尝试将字段名称显式传递给 addError()

I've tried passing nothing as parameters to checkDateFormat, I've tried to explicitly pass the field's name to addError()

$this->addError('username', '....');

但什么也没出现.

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

Which is the correct way to set a custom validation function?

推荐答案

您阅读文档了吗?

根据上面的验证步骤,一个属性会是当且仅当它是在场景()并与一个或多个活动规则相关联在 rules() 中声明.

According to the above validation steps, an attribute will be validated if and only if it is an active attribute declared in scenarios() and is associated with one or multiple active rules declared in rules().

所以你的代码应该是这样的:

So your code should looks like:

class SignupForm extends Model
{
    public function rules()
    {
        return [
            ['birth_date', 'checkDateFormat'],

            // other rules
        ];
    }

    public function scenarios()
    {
        $scenarios = [
            'some_scenario' => ['birth_date'],
        ];

        return array_merge(parent::scenarios(), $scenarios);
    }

    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.'));
    }
}

在控制器设置场景中,示例:

And in controller set scenario, example:

$signupForm = new SignupForm(['scenario' => 'some_scenario']);

这篇关于Yii2:如何为 activeform 使用自定义验证功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆