Omar Tariq
Omar Tariq

Reputation: 7724

Yii2 - Make Form Validator For URL Type To Skip "http://" in the start

This is how my yii2 model looks like:-

namespace app\models;

use Yii;
use yii\base\Model;


class UrlForm extends Model
{
    public $url;
    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [            
            [['url'], 'required'],
            ['url', 'url'],            
        ];
    }

}

I want it to approve the url if use has not written 'http://' in the start.

Example:-

stackoverflow.com should work fine.

http://stackoverflow.com should work fine.

Current Status:-

stackoverflow.com not accepted.

http://stackoverflow.com is accepted..

Upvotes: 0

Views: 510

Answers (2)

Joe Miller
Joe Miller

Reputation: 3893

You just need to add 'defaultScheme' => 'http' to your validation rule, so

public function rules()
    {
        return [            
            [['url'], 'required'],
            ['url', 'url', 'defaultScheme' => 'http'],            
        ];
    }

Upvotes: 1

Don Larynx
Don Larynx

Reputation: 695

Test if the parameter URL (most likely as a string) contains http:// at the beginning; if (doesntcontainHTTP){addHttpToURL();}

Example:

class UrlForm extends Model
{
    public $url;
    /**
     * @add "http://" to the url in here
     */
    public function rules()
    {
        /**
         * @Place the if statement here
         */
        return [            
            [['url'], 'required'],
            ['url', 'url'],            
        ];
    }

}

Upvotes: 0

Related Questions