简体   繁体   English

Yii2客户端验证

[英]Yii2 Client Side Validation

In Yii2 I have a conditional validation in the model.php. 在Yii2中,我在model.php中有条件验证。 When I write in the textfield something that doesn't pass the validation, it doesn't appear an error message after leaving the field. 当我在文本字段中编写未通过验证的内容时,离开字段后不会显示错误消息。 Only after a klick on create an error message appears. 只有在点击 创建后, 才会出现错误消息。 What do I have to make a message appears after writing something in a field. 在字段中写入内容后,我需要发出什么消息。

<?php
['state', 'required', 'when' => function ($model) {
    return $model->country == 'USA';
}, 'whenClient' => "function (attribute, value) {
    return $('#country').val() == 'USA';
}"]

You should set enableAjaxValidation in ActiveForm 您应该在ActiveForm中设置enableAjaxValidation

For example: 例如:

$form = ActiveForm::begin([
    'id' => 'contact-form',
    'enableAjaxValidation' => true,
]);

Maybe i have described the problem not so good so I try it again. 也许我描述的问题不是很好,所以我再试一次。 The problem is that the conditional validation only works after a click on save/create. 问题是条件验证仅在单击保存/创建后才能起作用。

In your model: 在您的模型中:

 public function rules()
 {
    return [
        ['state', 'required', 'targetClass' => '\backend\models\State', 
        'message' => 'Your message here'],
    ];
 }

I am not sure that your model is in backend, so you can correct that as you want. 我不确定您的模型在后端,因此您可以根据需要进行更正。

In Controller you have to create function like that: 在Controller中,您必须创建如下函数:

public function actionValidation(){
    $model = new State();
    if(Yii::$app->request->isAjax && $model->load(Yii::$app->
    request->post())){
        Yii::$app->response->format = 'json';
        return ActiveForm::validate($model);
    }     
}

An one more step, in your form on the beginning: 首先,以您的形式进行的一步:

<?php $form = ActiveForm::begin(
                [
                    'enableAjaxValidation' => true,
                    'validationUrl' => Url::toRoute('state/validation')
                ]
        ); ?>

Be careful, in code above I wrote 'state/validation', 'state' is name of controller where you put validation action. 注意,在上面的代码中,我写了“状态/验证”,“状态”是放置验证动作的控制器的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM