Skip to content Skip to sidebar Skip to footer

Yii2 Form Validation Not Working

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 undefin

Solution 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 :

functioncheckForm(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) {
        returntrue;
    }
    returnfalse;
}

call it :

checkForm("formId"); // it will be returntrue/falseand also validating the form

Solution 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

<divclass="form-group" ><?= Html::activeLabel($model, 'first_name', ['class'=>'control-label col-sm-3']); ?><divclass="col-sm-6"><?= Html::activeTextInput($model, 'first_name',['class' => ['form-control']]); ?><?= Html::error($model, 'first_name',['style' => 'color:red;']); ?></div></div>

Post a Comment for "Yii2 Form Validation Not Working"