在Symfony中验证不带"http://"的URL

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://的情况下进行验证?


2
为什么不要求用户输入正确的URL呢?或者添加一些JavaScript来在URL中没有协议时添加http://。这样他们甚至会知道它应该在那里。 - ThiefMaster
ThiefMaster,有许多情况下您不希望在数据库中硬编码URL协议。 - Acyra
3个回答

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)://)?表示协议现在是可选的。请参考sfValidatorUrl中的原始模式(REGEX_URL_FORMAT常量)。

1

如果您想要进行验证,可以使用本地 PHP 函数 filter_var 并带上 FILTER_VALIDATE_URL 标志。


-1

只需将“required”选项设置为false(默认为true)。

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

2
抱歉,但必须将其减1。这只是避免问题,而不是解决问题。最好使用sfValidatorPass();。 - Inoryy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接