简体   繁体   English

Yii2 使用 javascript 验证 ActiveForm

[英]Yii2 validate an ActiveForm with javascript

I have a working Active Form, which can be submitted, and validated via Yii PHP.我有一个有效的活动表格,可以通过 Yii PHP 提交和验证。 However, I would like to determine if the form is valid, when clicking a Next button.但是,我想在单击Next按钮时确定表单是否有效。

I can pass error messages to the user via this:我可以通过以下方式将错误消息传递给用户:

$("#form").yiiActiveForm("validate", true);

But this function doesn't return anything;但是这个 function 没有返回任何东西; I don't know if there are indeed any errors or not.我不知道是否确实有任何错误。 I tried this:我试过这个:

$error_count = document.getElementsByClassName("help-block").length

but this does not work;但这不起作用; the errors are counted before the UI has updated.在 UI 更新之前计算错误。 If I press the button again, a second time, then error_count is what I'd expect.如果我再次按下按钮,第二次,那么error_count就是我所期望的。

This doesn't seem to do anything:这似乎没有做任何事情:

$("#form").yiiActiveForm("validate");

I also tried this:我也试过这个:

$('#form').on('afterValidate', function (event, messages, errorAttributes) {}

But this is only triggered after the fact so I'm not sure what to do.但这只是在事后触发,所以我不知道该怎么做。

Any advice would be appreciated.任何意见,将不胜感激。

If you need to react to button you simply need to combine both events:如果您需要对按钮做出反应,您只需将两个事件结合起来:

let isNextClicked = false;

$('.next-btn').on('click', function(e) {
    e.preventDefault();
    isNextClicked = true;
    $("#form").yiiActiveForm("validate", true);
});

$('#form').on('afterValidate', function(event, messages, errorAttributes) {
    if (!isNextClicked) {
        //validation wasn't triggered by clicking next
        return;
    }

    // reset the state
    isNextClicked = false;

    if (errorAttributes.length > 0) {
        //there are errors so we won't let user to continue
        //we can also show some alert() here
        return;
    }
    
    // ... code to show the next tab of form ...
});

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

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