4
votes

I have one form which has multiple inputs with same name which are dynamically added using jQuery. Input names are as below:

ModelName[dynamic_name][]
ModelName[dynamic_name][]

I have also declared dynamic_name as public variable in a Model. How can I validate the above inputs using yii2 validation rule?

2

2 Answers

5
votes

Since your dynamic_name variable will be an array of input values, you can use the new each validator. It was added in v2.0.4. It takes an array and passes each element into another validator.

For example, to check if each element is an integer:

[['dynamic_name'], 'each', 'rule' => ['integer']],
1
votes

yii2, you can use with Class yii\validators\EachValidator

VIEW

<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'dynamic_name[]')->textInput() ?>
<?= Html::submitButton('Submit', ['class' => 'btn', 'name' => 'hash-button']) ?>
<?php ActiveForm::end(); ?>

MODEL

class MyModel extends Model
{
  public $dynamic_name = [];
  public function rules()
  {
    return [
        // checks if every dynamic_name is an integer
        ['dynamic_name', 'each', 'rule' => ['integer']],
    ]
 }
}

Note: This validator will not work with inline validation rules in case of usage outside the model scope, e.g. via validate() method.

Link: http://www.yiiframework.com/doc-2.0/yii-validators-eachvalidator.html