Yii2 validation rule for multiple inputs with the same name
I have one form that has multiple inputs with the same name that are dynamically added using jQuery. The input names are as follows:
ModelName[dynamic_name][]
ModelName[dynamic_name][]
I also declared dynamic_name
as a public variable in Model
. How can I validate the above data with yii2 validation rule?
source to share
Since your variable dynamic_name
will be an array of input values, you can use the new each
validator. It was added in version 2.0. It takes an array and passes each element to a different validator.
For example, to check if each element is an integer:
[['dynamic_name'], 'each', 'rule' => ['integer']],
source to share
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 built-in validation rules when used outside the scope of the model, for example. via the validate () method.
Link: http://www.yiiframework.com/doc-2.0/yii-validators-eachvalidator.html
source to share