【问题标题】:How to reinitialize model when client side validation fails in Yii 2?Yii 2中客户端验证失败时如何重新初始化模型?
【发布时间】:2016-12-09 06:43:02
【问题描述】:

我正在处理 Yii 2 表单,我想在客户端验证失败时重新初始化模型。例如具有如下某些规则:

public function rules()
{
    return [
        [['username'], 'required', 'message' => 'You must enter your username'],
        ['username','email'],
        [['password'], 'required', 'message' => 'You must enter your password'],           
    ];
}

当验证失败时,我希望所有字段都为空(例如,当用户输入无效的电子邮件地址时)。我该怎么做?

【问题讨论】:

    标签: validation model-view-controller model yii2 yii2-advanced-app


    【解决方案1】:

    我假设你使用标准 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]);
    

    更新:对于客户端验证,请在视图中添加此 JS 代码:

    $("#form-ID").on("afterValidateAttribute", function (event, attribute, messages) {
        if (event.result === false) {
            attribute.value = "";
        }
    });
    

    用适当的表单元素JS标识符替换#form-ID

    【讨论】:

    • 是的,我已经这样做了,但这是在发布之后,所以页面会刷新,这就是为什么我问是否有任何可能的方法来不刷新页面
    • 我正在使用 afterValidate 而不是 afterValidateAttribute,它工作正常,它给了我另一个想法,非常感谢你
    猜你喜欢
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多