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?

2 Answers 2

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']],
Sign up to request clarification or add additional context in comments.

8 Comments

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 ?
Are you validating via Ajax?
No because if I do enableAjaxValidation true then other validation does not work
What do you mean by other validation?
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.
|
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.