Get values from list of text input fields

I’m creating list of text input boxes using loop. How to get value from each field and implement basic validation like input cannot left blanked and minimum length of input string should be 20.

I try this code but the custom validation to check minimum length of input string is not working.

view code


$arr = array("config", "specs");


for($i=0; $i<count($arr); $i++){

    echo '<h3>' . $arr[$i] . '</h3>';

    for($j=0; $j<3; $j++){

        echo $form->field($model, "$arr[$i][$j]")->label(false);

    }

}

Model code:


public $config;

public $specs;


/**

 * @return array the validation rules.

 */

public function rules()

{

    return [

        [['config', 'specs'], 'required'],

        [['config', 'specs'], 'validateSpecs']

    ];

}


public function validateSpecs($attribute, $params)

{

    if(!is_array($this->$attribute) || count(array_filter($this->$attribute)) != 3){

        $this->addError($attribute, 'Error: Invalid input');

    } else{

        foreach ($this->$attribute as $key=>$value){

            if(!is_string($value) || strlen($value) < 20){

                $this->addError($attribute, 'Error: Invalid input');

            }

        }

    }

}

http://www.yiiframework.com/doc-2.0/guide-input-validation.html#implementing-client-side-validation

Have you considered this approach?

http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html

I tried tabular input, here is my updated code. Now length validation works but all the three input related to a category show error/success simultaneously.

View Code:


$arr = array("config", "specs");

foreach($arr as $index=>$value){

    echo '<h3>' . $value . '</h3>';

    for($i=0; $i<3; $i++){

        echo $form->field($config_model, "[$index]config")->label(false);

    }

}

Model Code:


class ConfigForm extends Model

{

    public $config;


    public function rules()

    {

        return [

            ['config', 'required'],

            ['config', 'string' , 'min' => 20],

        ];

    }

}

Also, Is it possible to do this without using additional model. Like using custom validation in my previous code.