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

Lui*_*nna 23 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.'));
    }
}
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)

但没有出现.

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

Tom*_*ane 11

你看过文档了吗?

根据上述验证步骤,当且仅当属性是scenario()中声明的活动属性且与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.'));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

$signupForm = new SignupForm(['scenario' => 'some_scenario']);
Run Code Online (Sandbox Code Playgroud)

  • 您确定,这种情况与此问题有关吗?如果您的解决方案有效,那么我宁愿称之为副作用.根据[这个答案](http://stackoverflow.com/a/26859043/1469208),真正的问题是将自定义验证器的`skipOnEmpty`设置为`false`,因为默认设置为`true`这就是导致它不被执行的原因.似乎,这种情况与OP的问题没有多少共同之处. (3认同)
  • 你不仅错了,而且绝对错了。没有必要声明场景。 (2认同)

Sud*_*rma 8

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

参考文献: - yii中的表格验证2


Mic*_*yen 6

尝试强制在空字段上进行验证

['birth_date', 'checkDateFormat', 'skipOnEmpty' => false, 'skipOnError' => false],
Run Code Online (Sandbox Code Playgroud)

此外,请确保您未birth_date在视图中为您的字段指定ID .

如果您确实有自己的ID birth_date,则需要指定selectors

<?= $form->field($model, 'birth_date', ['selectors' => ['input' => '#myBirthDate']])->textInput(['id' => 'myBirthDate']) ?>
Run Code Online (Sandbox Code Playgroud)


小智 5

$model->validate()如果从类Model扩展,则需要触发某处.


Mih*_* P. -1

您有机会使用客户端验证吗?如果这样做,那么您必须编写一个 javascript 函数来验证输入。您可以在这里查看他们是如何做到的:

http://www.yiiframework.com/doc-2.0/guide-input-validation.html#conditional-validation

另一个解决方案是禁用客户端验证,使用 ajax 验证,这也会返回错误。

还要确保您没有覆盖输入的模板,这意味着如果您覆盖了它,请确保其中仍然有 {error}。