Change the error message in inserting a url with $ form -> $ filed

Viewed 32

I want to change the error message that comes out when you enter a url wrong. I show you what I mean:

Image

The message must become: Inserisci un URL valido. Es: https://www.google.it

I am modifying the view.php generated automatically by gii. Here is the code:

<?= $form->field($model, 'link')->input('url')?>

This is the function I use to enter a valid url.

1 Answers

You can change the rules in your model for the attribute link using an inline validator:

public function rules()
{
    return [
        [['link'], 'required'],
        ['link', function ($attribute, $params, $validator) {
            // Check validity of attribute
            if ($this->$attribute != ...) {
                $this->addError($attribute, 'Inserisci un URL valido. Es: https://www.google.it');
            }
        }],    
    ];
}

When checking the validity of the $link attribute, you also can use the Yii2 UrlValidator.

Related