I've one field in my big form i.e.
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
Following is my ActiveForm options configuration:
<?php
$form = ActiveForm::begin([
//'id' => 'printerForm',
'enableClientValidation' => true,
'options' => [
'enctype' => 'multipart/form-data',
]
]);
?>
I want to implement client side unique validation for this. I'm using unique validator for it but its only working for server side validation.
public function rules() {
return [
[['name'], 'unique'],
]
...
other validations
...
};
Other validations working perfectly but unique client side validation is not working.
Finally I did it myself by enabling AJAX validation for a single input field and by using isAjax so that the server can handle the AJAX validation requests.
Following is the code:
In view:
<?= $form->field($model, 'name',['enableAjaxValidation' => true, 'validateOnChange' => false])->textInput(['maxlength' => 255]) ?>
And in controller:
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$nm= $_POST['BusinessProcessProfile']['name'];
$result = Model::find()->select(['name'])->where(['name' => "$nm"])->one();
if ($result) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return \yii\widgets\ActiveForm::validate($model, 'name');
} else {
return false;
}
}
It automatically calls validations rules defined in the Model.
For more info please refer : http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With