6

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?

AsgarAli
  • 2,201
  • 1
  • 20
  • 32

2 Answers2

5

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']],
topher
  • 14,790
  • 7
  • 54
  • 70
  • Thanks. Your code works fine if these kind of multiple inputs already exist in a form but when I add new inputs using jQuery in a form then it does not work. So please can you assist me for that ? – AsgarAli Jun 10 '15 at 06:56
  • 1
    Are you validating via Ajax? – topher Jun 10 '15 at 07:38
  • No because if I do enableAjaxValidation true then other validation does not work – AsgarAli Jun 10 '15 at 11:06
  • What do you mean by other validation? – topher Jun 10 '15 at 12:59
  • Other validation means to validate other inputs except this dynamic input. – AsgarAli Jun 10 '15 at 16:11
  • If I print $midel->errors then I am getting error messages respective to this dynamic inputs but error messages are not show in HTML form without using Ajax Validation – AsgarAli Jun 10 '15 at 16:17
  • 3
    Hmm. This changes your question entirely. Ask a new question with these details. Also include the code for your view and the javascript for creating the inputs in the question. That way someone who doesn't have to be me can answer the question. – topher Jun 10 '15 at 17:48
  • @topher ,yes i am stuck in same situation and i am validation through ajax ,http://stackoverflow.com/questions/31286133/yii2-add-dynamic-form-fields-and-their-validations – Gaurav Parashar Jul 12 '15 at 07:02
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

Dharmendra Singh
  • 1,186
  • 12
  • 22