我想在yii2中進行自定義驗證,但這不起作用。在yii2表單驗證中顯示錯誤
我想什麼是驗證每當卡車狀態不是17或18即如果例如它的12應返回該錯誤,但始終顯示錯誤
public function validateRegno()
{
$truck = TblTrucks::find()->where(["reg_no"=>$this->reg_no])->all();
if ($truck) {
if(!$truck->truck_status ==18 || !$truck->truck_status ==17){
$this->addError('reg_no', 'The truck is not yet cleared by customer service');
}
}
}
這些都是模型的規則
public function rules()
{
return [
[['reg_no', 'truck_category', 'added_by', 'truck_status', 'driver_name'], 'required'],
[['truck_category', 'added_by', 'truck_status', 'is_normal'], 'integer'],
[['added_on'], 'safe'],
[['reg_no'], 'string', 'max' => 50],
['reg_no', 'validateRegno','on' => 'create'],
}
這是我的形式
<?php $form = ActiveForm::begin(['id' => $model->formName(),
'enableAjaxValidation' => true,
//'enableClientValidation' => true,
'validationUrl' => ['truck/validate'],
]); ?>
在控制器
(truck/validate)
public function actionValidate(){
$model = new TblTrucks();
$model->scenario = 'create';
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
if (!$model->validate()) {
Yii::$app->response->format='json';
return ActiveForm::validate($model);
}
}
}
在表單上使用''enableAjaxValidation'=> true'並且添加'if(Yii :: $ app-> request-> isAjax && $ model-> load(Yii :: $ ()){ Yii :: $ app-> response-> format = \ yii \ web \ Response :: FORMAT_JSON; return ActiveForm :: validate($ model); }'在行動部分 – GAMITG
但它沒有這樣做 –
你會得到錯誤? – GAMITG