本文介绍了Yii2 whenClient验证问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,我无法获得必需的条件规则才能起作用。即使我将条件降低为始终返回false,但要求验证似乎会检查此不必要的字段:

For some reason I cannot get conditional rule 'required' to work. Even if I reduce the condition to "always return false", required-validation seems to check this unnecessary field:

public function rules() {
    return [
        [['order_id', 'product_id', 'quantity'], 'required'],

        ['product_date', 'required',
         'whenClient' => "function(attribute, value) {
                              return false;
                          }"
        ],

       // more rules here
        [['date_create', 'date_update', 'product_date'], 'safe'],
        // more rules here
    ];
}

在表单上提交save()失败,并且$ model-> getErrors()点到product_date作为必填字段。我错过了什么?预先谢谢您。

On form submit save() fails and $model->getErrors() points to product_date as a necessary field. What have I missed? Thank you in advance.

推荐答案

您还应该在规则中添加服务器端条件(文档:):

You should add the server-side condition to the rule as well (documentation: when):

['product_date', 'required',
 'when'       => function ($model) {
                     return false;
                 },
 'whenClient' => "function(attribute, value) {
                      return false;
                  }"
],

whenClient 仅适用于客户端的JS。提交表单后,验证也必须在服务器上完成(或跳过)。如果您具有 whenClient 定义,通常应该具有 when 定义。 when 的定义更为重要, whenClient 只是为了改善用户体验。

whenClient is only for JS on the client side. When the form gets submitted the validation has to be done (or skipped) at the server as well. Usually you should have a when definition if you have whenClient definition. The when definition is much more important, whenClient is just to improve the user experience.

查找更多信息。

这篇关于Yii2 whenClient验证问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 12:35