Yii2 whenClient validation issue

冷暖自知 提交于 2019-12-11 02:13:54

问题


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
    ];
}

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


回答1:


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

Find more infos here.




回答2:


Replace

['product_date', 'required', 

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

With

['product_date', function(attribute, value) {
        return false;
    }],


来源:https://stackoverflow.com/questions/30071890/yii2-whenclient-validation-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!