【问题标题】:Conditional validation if input field is empty or not?如果输入字段为空,则进行条件验证?
【发布时间】:2016-12-14 04:30:39
【问题描述】:

我有包含地址、国家、地区字段的表格。如果地址不为空,则需要国家和地区。如果地址为空,则不需要国家、地区。

我使用conditional validation as document says在表模型规则中定义这样的方法

public function rules()
{
    return [
        [['username', 'password', 'email', 'tanggal_daftar','password_validate'], 'required'],
        [['customer_id','propinsi_id', 'kota_id', 'kecamatan_id', 'user_status_id','poin'], 'integer'],
        [['tanggal_daftar','mobile_token','fb_id','newsletter','agree','password_validate','old_password'], 'safe'],
        [['username', 'jenis_kelamin'], 'string', 'max' => 10],
        [['password'], 'string', 'max' => 70],
        [['identitas'], 'required', 'on' => 'login'],
        [['email','username'], 'unique','except' => 'login'],
        [['email'],'email'],
        [['nama', 'hobby', 'pekerjaan'], 'string', 'max' => 30],

        //address field 
        [['alamat'], 'string', 'max' => 200],

        //country field
        [['negara_id'], 'string', 'max' => 3],

        [['kode_pos'], 'string', 'max' => 6],
        [['hp'], 'string', 'max' => 18],
        [['is_agent'],'boolean'],
        [['profile_picture'],'string','max' => 100],
        [['password_validate'], 'compare', 'compareAttribute'=>'password', 'message'=>Yii::t('app', 'Password tidak sama')],
        [['agree'],'compare','operator' => '==','compareValue' => true,'message' => ''],

//country field     
[['country_id'], 'required', 'when' => function($model){
                return $model->address != null;
                .. 
                what about the code if address is empty then country not required??
 }],

我的看法

...
... 
.. address field ..
<?= $form->field($model, 'alamat')->textInput(['maxlength' => true,'class'=>'input_text'])->label('Address')?>

... country field drop down ..
<?= $form->field($model, 'negara_id')->dropDownList(ArrayHelper::map(TbNegara::find()->all(), 'negara_id', 'negara_name'),['prompt'=>'-- Pilih Negara --','id'=>'negara_id','class'=>'input_select'])->label('Country') ?>
...
...

如果我测试上面的代码,无论我的表单中的地址是否为空,那么国家字段总是需要的。

我做错了吗?

更新

当地址不为空时,国家是必需的。

所以如果我在地址字段中输入并按下提交按钮,它会显示所需的错误,然后如果我在地址字段中没有输入任何内容并按下提交按钮,它将处理提交。

解决办法是

开头没有'enableAjaxValidation' =&gt; true,

这是我的国家字段表模型规则

[['negara_id'], 'required', 'when' => function($model){
                return $model->alamat != null;
            }, 'whenClient' => "function (attribute, value){
                return $('#tbcustomer-alamat').val() != '';
            }"],

现在我在实现这段代码时遇到了其他类似的问题

[['propinsi_id'], 'required', 'when' => function($model){
                //district required if country is set
                return $model->negara_id != null;
            }, 'whenClient' => "function (attribute, value){
                return $('#negara_id').val() != '';
            }"],

即使设置了国家也不需要地区,如果设置了国家则需要。

所以如果我输入地址并设置国家,并将地区留空并按提交,它将处理提交但导致地区不能为空[ 'propinsi_id' =&gt; [ 0 =&gt; 'ID Propinsi cannot be blank.' ] ]

类似于我的验证工作在服务器端,但不在客户端。

在设置国家/地区时通过 ajax 加载地区

这是区域字段的视图

                <div class="form_grup leftside fl">
                    <div class="input_select">
                    <?php
                        if (isset($model->propinsi)){
                            echo $form->field($model, 'propinsi_id')->widget(DepDrop::classname(), [
                            'options'=>['id'=>'propinsi_id','class'=>'input_select'],
                            'data'=>[$model->propinsi_id=>$model->propinsi->propinsi_name],
                            'pluginOptions'=>[
                                'initialize' => true,
                                 //depends on country  
                                'depends'=>['negara_id'],
                                    'class'=>'input_select',
                                'placeholder'=>'-- Pilih Propinsi --',
                                'url'=>Url::to(['customer2/propinsi'])
                            ]
                        ]);
                        } else {
                            echo $form->field($model, 'propinsi_id')->widget(DepDrop::classname(), [
                                    'options'=>['id'=>'propinsi_id','class'=>'input_select'],
                                    'pluginOptions'=>[
                                            'initialize' => true,
                                            //depends on country  
                                            'depends'=>['negara_id'],
                                            'class'=>'input_select',
                                            'placeholder'=>'-- Pilih Propinsi --',
                                            'url'=>Url::to(['customer2/propinsi'])
                                    ]
                                    ]);
                        }
                    ?>
 <!--                       <i class="fa fa-angle-down"></i> -->
                    </div>
                </div>

我在区现场客户端验证方面做错了什么?

【问题讨论】:

  • 显示所有模型规则。
  • @InsaneSkull 完成。 :D
  • 那么,您是否需要对地区字段进行验证?我不清楚。
  • 如果设置了国家,则需要地区,如果没有设置国家,则不需要。就像如果地址不为空则需要国家,如果地址为空则不需要。

标签: yii2


【解决方案1】:

_form.php

<?php $form = ActiveForm::begin(['enableAjaxValidation' => true]); ?>

控制器

if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
   \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return \yii\widgets\ActiveForm::validate($model);
}

型号

[['country_id'], 'required', 'when' => function ($model) { return $model->address != null;}, 'enableClientValidation' => false ],
[['propinsi_id'], 'required', 'when' => function ($model) { return $model->country_id != null;}, 'enableClientValidation' => false ],

【讨论】:

  • 感谢它现在工作,但我有类似的问题。问题已更新。希望你有空闲时间。
  • 对不起,这意味着禁用客户端验证?问题出在客户端验证中。
  • @DarkCyber​​。 idk 可能是,但目前无法找到有关 clientValidation 的任何参考资料。
猜你喜欢
  • 2014-01-23
  • 2016-12-18
  • 1970-01-01
  • 2017-09-11
  • 2020-06-20
  • 2017-09-01
  • 1970-01-01
  • 2019-12-16
  • 2017-08-22
相关资源
最近更新 更多