我正在处理 Yii 2 表单,我想在客户端验证失败时重新初始化模型。例如,使用如下所示的某些规则:
public function rules()
{
return [
[['username'], 'required', 'message' => 'You must enter your username'],
['username','email'],
[['password'], 'required', 'message' => 'You must enter your password'],
];
}
当验证失败时,我希望所有字段都为空(例如,当用户输入无效的电子邮件地址时)。我怎样才能做到这一点?
最佳答案
我假设您使用标准 Yii 2 加载模型的方式:
$model = new SomeModel();
if ($model->load(\Yii::$app->request->post()) && $model->save()) {
// ...
}
return $this->render('view', ['model' => $model]);
验证失败时将字段设置为null
。您不想创建新实例(这会更容易),因为您会丢失所有验证消息。
$model = new SomeModel();
if ($model->load(\Yii::$app->request->post())) {
if ($model->save()) {
// ....
} else {
$model->username = null;
$model->password = null;
}
}
return $this->render('view', ['model' => $model]);
更新:为了进行客户端验证,请在 View 中添加以下 JS 代码:
$("#form-ID").on("afterValidateAttribute", function (event, attribute, messages) {
if (event.result === false) {
attribute.value = "";
}
});
将 #form-ID
替换为正确的表单元素 JS 标识符。
关于validation - Yii 2 中客户端验证失败时如何重新初始化模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41054534/