yii2 form validation not working

非 Y 不嫁゛ 提交于 2019-12-25 04:26:08

问题


How to know if the validation has been triggered in yii2 active form? I am using

$('#formId').yiiActiveForm('validate', true);

to validate the form, but it always returns undefined.


回答1:


Trigger the form validation try this :

var $form = $("#formId"), 
   data = $form.data("yiiActiveForm");
$.each(data.attributes, function() {
   this.status = 3;
});
$form.yiiActiveForm("validate");

I've create a function to validating active form in javascript, it will be return true/false. Maybe usefull :

function checkForm(form_id){
    var $form = $("#"+form_id), data = $form.data("yiiActiveForm");
    $.each(data.attributes, function() {
        this.status = 3;
    });
    $form.yiiActiveForm("validate");
    if ($form.find('.has-error').length == 0) {
        return true;
    }
    return false;
}

call it :

checkForm("formId"); // it will be return true/false and also validating the form



回答2:


Try

in your MODEL

For example,

 public function rules()

    {
        return [

            [['first_name', 'last_name', 'email_address','city','contact_phone', 'Address', 'date_created'], 'required'],

            ['contact_phone', 'unique'],

             ];

    }

first_name like input name in your view file

In your VIEW files

<div class="form-group" >

<?= Html::activeLabel($model, 'first_name', ['class'=>'control-label col-sm-3']); ?>

<div class="col-sm-6">

<?= Html::activeTextInput($model, 'first_name',['class' => ['form-control']]); ?>

<?= Html::error($model, 'first_name',['style' => 'color:red;']); ?>

</div>

</div>


来源:https://stackoverflow.com/questions/41424223/yii2-form-validation-not-working

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