js active form validation in yii2

六眼飞鱼酱① 提交于 2019-12-14 03:29:46

问题


I have a active form and I am trying to validate it using the script written below :

jQuery("#form").yiiActiveForm("submitForm");

The problem is, the script always returns false. But when I call it second time with some delay, it returns true.

jQuery("#form").yiiActiveForm("submitForm");
setTimeout(function () {
if (jQuery("#form").yiiActiveForm("submitForm")) {
        //ajax call...    
    }
}, 300);

My question is, how does validation works in yii2 ? And is there a better way to validate active forms in js?

When I use

jQuery("#form").yiiActiveForm("submitForm");

beforeSubmit handler is called.

$('#form').on('beforeSubmit', function (e) {
    alert('message');
});

Does beforeSubmit automatically validates the form?


回答1:


Simple

You should try this

<?php
    $this->registerJs('



            jQuery("#w0").yiiActiveForm("add",{
                "id": "customer-name",
                "name": "name",
                "container": ".field-customer-name",
                "input": "#customer-name",
                "error": ".help-block.help-block-error",
                "validate": function(attribute, value, messages, deferred, $form) {

                    yii.validation.required(value, messages, {
                        "message": "Name be blank bug."
                    });

                    yii.validation.string(value, messages, {
                        "message": "Name must be a string.",
                        "max": 255,
                        "tooLong": "Name should contain at most 255 characters.",
                        "skipOnEmpty": 1
                    });
                }
        });


    ');
 ?>

Changes

w0 into your form ID

"id": "customer-name" into your input field ID

"container": ".field-customer-name" into input field div container class


来源:https://stackoverflow.com/questions/41422316/js-active-form-validation-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!