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

查看:248
本文介绍了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天全站免登陆