Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, but google.com no. How can i this edit for validate without http:// ?

like image 828
Break Break Avatar asked Oct 10 '22 12:10

Break Break


2 Answers

I am afraid you will need to create your own custom validator:

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')));
  }
}

Here ((%s)://)? mean that now protocol is optional. See sfValidatorUrl for an original pattern (REGEX_URL_FORMAT const).

like image 130
melekes Avatar answered Oct 14 '22 03:10

melekes


For validating you could use the native PHP function filter_var with the flag FILTER_VALIDATE_URL.

like image 24
Raffael Avatar answered Oct 14 '22 02:10

Raffael