yii2yii2-basic-app

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


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.


Solution

  • 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.