Yii2 validation rule for multiple inputs with same

2019-05-09 18:48发布

问题:

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?

回答1:

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']],


回答2:

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



标签: yii2