我的大表格中有一个字段,即
<?= $form->field($model, 'name')->textInput(['maxlength' => 255]) ?>
以下是我的 ActiveForm 选项配置:
<?php
$form = ActiveForm::begin([
//'id' => 'printerForm',
'enableClientValidation' => true,
'options' => [
'enctype' => 'multipart/form-data',
]
]);
?>
我想为此实现客户端唯一验证。我正在为其使用独特的验证器,但它仅适用于服务器端验证。
public function rules() {
return [
[['name'], 'unique'],
]
...
other validations
...
};
其他验证工作正常,但独特的客户端验证不起作用。
最佳答案
最后,我通过为单个输入字段启用 AJAX 验证并使用 isAjax 使服务器可以处理 AJAX 验证请求来实现这一点。
代码如下:
在 View 中:
<?= $form->field($model, 'name',['enableAjaxValidation' => true, 'validateOnChange' => false])->textInput(['maxlength' => 255]) ?>
在 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;
}
}
它会自动调用模型中定义的验证规则。
更多信息请引用:http://www.yiiframework.com/doc-2.0/guide-input-validation.html#client-side-validation
关于javascript - Yii2 为输入字段实现客户端唯一验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33491565/