问题描述
我正在尝试使用指南中给出的 Yii2 的条件验证器,例如:
I am trying to use Yii2's conditional validator as given in the guide like:
型号代码
public function rules()
{
// $discharged = function($model) { return $this->discharged == 1; };
return [
[[ 'admission_date','discharge_date', 'doctor_appointment_date', 'operation_date'], 'safe'],
[[ 'package','tpa_name', 'discharged', 'bed_type', 'room_category', 'ref_doctor', 'consultant_doctor', 'operation_name'], 'integer'],
[['advance_amount', 'operation_charges'], 'number'],
[['patient_name', 'ref_doctor_other'], 'string', 'max' => 50],
[['general_regn_no', 'ipd_patient_id'], 'string', 'max' => 20],
[['admission_date', 'discharge_date', 'doctor_appointment_date', 'operation_date'],'default','value'=>null],
['ipd_patient_id', 'unique'],
[['bed_type','admission_date','room_category'],'required'],
['discharge_date', 'required', 'when' => function($model) {
return $model->discharged == 1;
}],
];
}
在我的控制器中:
public function actionCreate()
{
$model = new PatientDetail();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
但是无论我是否选择了复选框字段的出院字段,出院日期总是按要求返回.
But whether I select or not the discharged field which is a checkbox field, the discharge date alwasys returns as required.
我在这里做错了什么?
推荐答案
似乎 Yii2 默认会在 BOTH 服务端和客户端做验证.检查 Conditional Validation 部分中的示例">Yii2 文档:
It seems that by default Yii2 will do validation in BOTH Server side and Client side. Check the example in Conditional Validation
part of Yii2 doc:
['state', 'required', 'when' => function ($model) {
return $model->country == 'USA';
}, 'whenClient' => "function (attribute, value) {
return $('#country').val() == 'USA';
}"],
您还需要一个 'whenClient'
代码,或者如@Alexandr Bordun 所说,通过 'enableClientValidation' => 禁用客户端验证.错误
.
you also need a 'whenClient'
code, or as @Alexandr Bordun said, to disable the client validation by 'enableClientValidation' => false
.
这篇关于Yii2:条件验证器总是返回必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!