Yii2自定义表单验证

时间:2018-07-25 16:57:41

标签: javascript yii2

我需要在Yii2框架中实现自定义表单验证。

我的页面上有以下脚本:

<script src="/assets/acb8f29e/jquery.js"></script>
<script src="/assets/cb9d857a/yii.js"></script>
<script src="/assets/cb9d857a/yii.activeForm.js"></script>
<script src="/unify/assets/js/form.js"></script>

form.js内,我们具有函数initProfilePage

function initProfilePage(){
    $('#form_id').on('beforeValidate', function (e) {
            $('#form_id').yiiActiveForm('find', 'attribute').validate = function (attribute, value, messages, deferred, $form) {
                //Custom Validation
            }
        return true;
    });
}

在页面的最底部,我有以下脚本:

<script>
    jQuery(function ( $ ) {
        initProfilePage();    
        jQuery('#user-profile').yiiActiveForm(... here we have the validation parameter which works fine ...)
    });
</script>

表单显示正确,没有任何错误,但是当我提交表单时,出现以下错误:

TypeError: $(...).yiiActiveForm(...) is undefined

我在做什么错以及如何解决?

1 个答案:

答案 0 :(得分:1)

该错误的原因是,当您调用$('#form_id').yiiActiveForm('find', 'attribute')时,实际上在第一个参数中传递了函数名find,而在第二个参数中传递了要验证的输入。但这不应该是name属性,而应该是id,也应该是ActiveForm生成的model-attribute格式的属性。

它会为validate undefined引发错误,因为find方法返回undefined,而它应该返回要验证的输入的attributes,以及返回的原因undefined就是其中之一

  • 您没有为输入传递正确的ID。
  • 您正在"enableClientValidation"=>false配置中使用ActiveForm

要生成ActiveForm为您要验证的特定字段生成的确切名称,可以使用\yii\helpers\Html::getInputId($model,'attribute')

所以要像下面那样更改您的JavaScript

$this->registerJs ( "$('#form_id').on('beforeValidate', function (e) {
                $('#form_id').yiiActiveForm('find', '".Html::getInputId($model , 'name')."').validate = function (attribute, value, messages, deferred, \$form) {
                console.log('validating now');
            }
        return false;
    });", \yii\web\View::POS_READY);