Yii2 validation rule for multiple inputs with same name

旧城冷巷雨未停 提交于 2019-12-22 09:34:18

问题


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



来源:https://stackoverflow.com/questions/30738180/yii2-validation-rule-for-multiple-inputs-with-same-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!