Skip to content
Advertisement

Yii2 custom validation to array rule

I have a custom form model in yii2, and i have a rule for an array property:

public $permissionEmails;

public function rules() {
        return [
            ['permissionEmails', 'each', 'rule' => ['string']],
            ['permissionEmails', 'validatePermissionEmails'],
        ]
}

And In the view file, I put the fields in a foreach loop with an index start from 0:

<?php for ($i = 0; $i < ProfileAlertForm::MAX_EMAIL_FIELDS; $i++): ?>

    <?= $form->field($model, 'permissionEmails[' . $i . ']')->textInput(['id' => "profilealertform-permissionemails{$i}"])->label(Yii::t("label", "Email")) ?>                                            

<?php endfor; ?>

I want to write a custom validation (validatePermissionEmails) to validate every text input field that has an error, so if i write a non-email text to a second and fourth input, i want to see the error message (for example: “it is not an email”).

And i know, there is az email validator to a single property, i just wrote an example custom validator for my array property:

public function validatePermissionEmails($attribute, $params) {
    if ($this->$attribute) {
        $i=0;
        foreach ($this->$attribute as $index => $email) {  
            if(filter_var($email, FILTER_VALIDATE_EMAIL)===false) {
                $this->addError("permissionemails{$i}", Yii::t("error", "Not a valid email address")); 
            }
            $i++;
        }
    }
}

I get back the error messages from the ajax validation (for example,if i have 5 input fields and I don’t fill the 2. and 4. input texts with a right email string, the error result are:

{“profilealertform-permissionemails1”:[“Not a valid email address”],”profilealertform-permissionemails3″:[“Not a valid email address”],”flashMessages”:{“success”:””,”danger”:””,”warning”:””,”info”:””}}

But the error messages didn’t appear below the input fields. But I can’t send the form to save too, so the validation sees the error, just can’t show the messages.

Does anyone ever written a custom validation function for arrays?

Advertisement

Answer

I used to define the custom validation function for arrays like this:

...
 return [
   ['permissionEmails', 'each', 'rule' => ['string']],
   [['permissionEmails'], 'each', 'rule' => ['validatePermissionEmails']]
 ]
...
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement