用户名验证只能在服务器端进行,因为只有服务器才具有所需的信息。在这种情况下,您可以使用基于AJAX的验证。
步骤1-要启用AJAX验证,请以这种方式修改注册视图。
<?php
use yii\bootstrap\ActiveForm;
use yii\bootstrap\Html;
?>
<div class = "row">
<div class = "col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'registration-form',
'enableAjaxValidation' => true]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'email')->input('email') ?>
<?= $form->field($model, 'country') ?>
<?= $form->field($model, 'city') ?>
<?= $form->field($model, 'phone') ?>
<div class = "form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary',
'name' => 'registration-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>我们还应该准备服务器,以便它可以处理AJAX请求。
步骤2-以这种方式修改SiteController的actionRegistration方法。
public function actionRegistration() {
$model = new RegistrationForm();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request>post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
return $this->render('registration', ['model' => $model]);
}步骤3-现在,转到http:// localhost:8080 / index.php?r = site / registration,您会注意到表单验证是通过AJAX请求完成的。

作者:terry,如若转载,请注明出处:https://www.web176.com/yii/500.html
支付宝
微信