2011-07-14 122 views
5
$this->setValidator('website', new sfValidatorAnd(array(
      $this->validatorSchema['website'], 

      new sfValidatorUrl(array(), array(
      'invalid' => 'This is not website', 
     )),  
))); 

此驗證http://google.com,但google.com沒有。我如何編輯驗證沒有http://驗證URL:// symfony的

+2

爲什麼不讓用戶輸入正確的URL?或者添加一些JavaScript來預覽http://如果URL不包含協議。然後他們甚至知道它屬於那裏。 – ThiefMaster

+0

ThiefMaster,有很多用例你不想在數據庫中硬編碼url協議。 – Acyra

回答

4

恐怕你需要創建自己的自定義驗證:

class myCustomValidatorUrl extends sfValidatorRegex 
{ 
    const REGEX_URL_FORMAT = '~^ 
    ((%s)://)?         # protocol 
    (
     ([a-z0-9-]+\.)+[a-z]{2,6}    # a domain name 
     |         # or 
     \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} # a IP address 
    ) 
    (:[0-9]+)?        # a port (optional) 
    (/?|/\S+)        # a /, nothing or a/with something 
    $~ix'; 

    protected function configure($options = array(), $messages = array()) 
    { 
    parent::configure($options, $messages); 

    $this->addOption('protocols', array('http', 'https', 'ftp', 'ftps')); 
    $this->setOption('pattern', new sfCallable(array($this, 'generateRegex'))); 
    } 

    public function generateRegex() 
    { 
    return sprintf(self::REGEX_URL_FORMAT, implode('|', $this->getOption('protocols'))); 
    } 
} 

這裏((%s)://)?意味着現在的協議是可選的。 對於原始模式(REGEX_URL_FORMAT常量),請參閱sfValidatorUrl

+0

謝謝!我很酷!:) – denys281

-1

只需將「required」選項設置爲false(默認情況下爲true)。

$this->setValidator('url', 
    new sfValidatorUrl(array('required' => false), array(
    'invalid' => 'invalid url'))); 
+2

對不起,但不得不-1。這是爲了避免這個問題,而不是解決問題。不妨使用sfValidatorPass();然後。 – Inoryy

1

爲了驗證你可以使用原生的PHP函數filter_var旗FILTER_VALIDATE_URL。