验证symfony中没有http://的url


validate url without http:// in symfony

  $this->setValidator('website', new sfValidatorAnd(array(
          $this->validatorSchema['website'],
          new sfValidatorUrl(array(), array(
            'invalid' => 'This is not website',
          )),    
  )));

this validate http://google.com,但是google.com no。如果没有http://,我如何编辑验证?

恐怕您需要创建自己的自定义验证器:

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 const)

您可以使用带有FILTER_VALIDATE_URL标志的本地PHP函数filter_var进行验证。

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

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