【问题标题】:validate url without http:// in symfony在 symfony 中验证没有 http:// 的 url
【发布时间】:2011-07-14 08:43:21
【问题描述】:
  $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?如果 URL 不包含协议,或者添加一些 JavaScript 来前置 http://。然后他们甚至会知道它属于那里。
  • ThiefMaster,有很多用例你不想在数据库中硬编码 url 协议。

标签: php validation symfony1 symfony-1.4


【解决方案1】:

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

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 const),请参阅 sfValidatorUrl

【讨论】:

    【解决方案2】:

    为了验证,您可以使用带有 FILTER_VALIDATE_URL 标志的原生 PHP 函数 filter_var

    【讨论】:

      【解决方案3】:

      只需将“必需”选项设置为 false(默认情况下为 true)。

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

      【讨论】:

      • 抱歉,必须 -1。这是在回避问题,而不是解决问题。不妨使用 sfValidatorPass();那么。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多