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

标签 forms validation yii2

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

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

当我按下提交按钮时,错误消息不会出现在表单 View 的字段下,而其他规则(如所需的电子邮件和密码)会出现。

我正在处理 Signup 原生表单,所以为了确保它不是一个归档问题,我已经设置了规则
['username', 'checkDateFormat']

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

我试过不将任何内容作为参数传递给 checkDateFormat ,我已尝试将字段名称显式传递给 addError()
$this->addError('username', '....');

但什么也没有出现。

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

最佳答案

你读过文档吗?

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().



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

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

在 Controller 设置场景中,例如:

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

关于forms - Yii2:如何为 activeform 使用自定义验证功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27805133/

相关文章:

c# - 如何在 C# Visual Studio 2010 中使用另一个窗体中的组件

forms - 使用变量定义表单输入中的默认值

bootstrap-4 - Yii2 - 将 Bootstrap 3 升级到 4

javascript - Angular:Validators.email 如果为空则无效

javascript - checkValidity 更新 UI

<f :viewParam> do not localize to <f:view locale>, 但到默认语言环境的验证/转换错误

javascript - jquery 文本区域中的最大字符数

yii2 - yii2 的 web.config(提供的 .htaccess 文件)

ajax - YII2 gridview使用ajax自定义搜索

forms - 如何在 Ember.js 应用程序中获取输入值?