js active form validation in yii2

2019-09-20 03:56发布

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条回答
仙女界的扛把子
2楼-- · 2019-09-20 04:17

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
查看更多
登录 后发表回答