yii2 form validation not working

2019-09-15 02:44发布

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.

2条回答
闹够了就滚
2楼-- · 2019-09-15 02:48

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
查看更多
倾城 Initia
3楼-- · 2019-09-15 03:01

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