Note that this validator only checks if the URL scheme and host part are correct. It does not check the remaining parts of a URL.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends Validator
コード例 #1
0
 /**
  * @param string $value the URL
  *
  * @throws InvalidConfigException
  */
 public function setUrl($value)
 {
     $error = null;
     $validator = new UrlValidator();
     if (!$validator->validate($value, $error)) {
         throw new InvalidConfigException($error);
     }
     $this->url = $value;
 }
コード例 #2
0
 public static function generationFullLink($link, $title = '')
 {
     $validator = new UrlValidator();
     if (!$validator->validate($link, $error)) {
         $error = 'Укажите верную ссылку, пример http://site.ru/link';
     } else {
         return 'http://' . Yii::$app->getModule('short_link')->domain . '/l/' . self::saveLink($link, $title);
     }
     return false;
 }
コード例 #3
0
 /**
  * Создание короткой ссылки
  * @return array
  */
 public function actionNew()
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     $error = $short_link = false;
     $link = Yii::$app->request->post('link');
     $title = Yii::$app->request->post('title');
     $validator = new UrlValidator();
     if (!$validator->validate($link, $error)) {
         $error = 'Укажите верную ссылку, пример http://site.ru/link';
     } else {
         $short_link = 'http://' . $this->module->domain . '/l/' . ShortLinks::saveLink($link, $title);
     }
     return ['short_link' => $short_link, 'status' => $short_link ? true : false, 'error' => $error];
 }
コード例 #4
0
ファイル: LinkController.php プロジェクト: jorry2008/turen
 /**
  * 所有的广告入口
  * @param string $name 广告标识
  * @param string $key 跟踪代码,表示广告来源,默认为pc站内广告
  */
 public function actionAdClick($name, $key = '')
 {
     $model = Ad::findOne(['short_code' => trim($name)]);
     if ($model) {
         //根据$key各种统计与分析
         //增加一次点击
         $model->hits = $model->hits + 1;
         $model->save(false);
         //验证url是否合法
         $v = new UrlValidator();
         if ($v->validate($model->link_url)) {
             //跳转到广告指定的位置
             $this->redirect($model->link_url);
         }
     }
     //网站直接404
     throw new NotFoundHttpException('The requested page does not exist.');
 }
コード例 #5
0
 public function createLink($name, $original)
 {
     $url = $original;
     $validator = new UrlValidator();
     if ($validator->validate($url) == false) {
         $url = '/' . ltrim($url, '/');
         $value = parse_url($url);
         if (isset($value["path"])) {
             $config = [];
             if (isset($value["query"])) {
                 parse_str($value["query"], $config);
             }
             array_unshift($config, $value["path"]);
             $url = $config;
         }
     }
     return [$name, $url];
 }
コード例 #6
0
ファイル: UrlValidatorTest.php プロジェクト: howq/yii2
 public function testValidateAttributeAndError()
 {
     $obj = new FakedValidationModel();
     $obj->attr_url = 'http://google.de';
     $val = new UrlValidator();
     $val->validateAttribute($obj, 'attr_url');
     $this->assertFalse($obj->hasErrors('attr_url'));
     $this->assertSame('http://google.de', $obj->attr_url);
     $obj = new FakedValidationModel();
     $val->defaultScheme = 'http';
     $obj->attr_url = 'google.de';
     $val->validateAttribute($obj, 'attr_url');
     $this->assertFalse($obj->hasErrors('attr_url'));
     $this->assertTrue(stripos($obj->attr_url, 'http') !== false);
     $obj = new FakedValidationModel();
     $obj->attr_url = 'gttp;/invalid string';
     $val->validateAttribute($obj, 'attr_url');
     $this->assertTrue($obj->hasErrors('attr_url'));
 }
コード例 #7
0
ファイル: Otp.php プロジェクト: sam002/yii2-otp
 public function init()
 {
     parent::init();
     if ($this->algorithm === self::ALGORITHM_TOTP) {
         $this->otp = OtpHelper::getTotp($this->lable, $this->digits, $this->digets, $this->interval);
     } elseif ($this->algorithm === self::ALGORITHM_HOTP) {
         $this->otp = OtpHelper::getHotp($this->lable, $this->digits, $this->digets, $this->counter);
     } else {
         throw new InvalidConfigException('otp::$algorithm = \\"' . $this->algorithm . '\\" not allowed, only Otp::ALGORITHM_TOTP or Otp::ALGORITHM_HOTP');
     }
     if (!empty($this->imgLabelUrl) && is_string($this->imgLabelUrl)) {
         $validator = new UrlValidator();
         if ($validator->validate($this->imgLabelUrl)) {
             $this->otp->setImage($this->imgLabelUrl);
         } else {
             throw new InvalidConfigException($validator->message);
         }
     }
 }
コード例 #8
0
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     // Validate given parameters
     $className = self::className();
     $urlValidator = new UrlValidator(['enableIDN' => extension_loaded('intl')]);
     if (empty($this->endpoint) || !$urlValidator->validate($this->endpoint)) {
         throw new InvalidConfigException("Class \"{$className}\" requires a valid URL to Wordpress XML-RPC API endpoint to be set in \"\$endpoint\" attribute.");
     }
     if (empty($this->username) || empty($this->password)) {
         throw new InvalidConfigException("Class \"{$className}\" requires a valid Wordpress credentials to be set in \"\$username\" and \"\$password\" attributes.");
     }
     if (!is_array($this->proxyConfig)) {
         throw new InvalidConfigException("Class \"{$className}\" requires \"\$proxyConfig\" to be given in array format.");
     }
     if (!is_array($this->httpAuthConfig)) {
         throw new InvalidConfigException("Class \"{$className}\" requires \"\$httpAuthConfig\" to be given in array format.");
     }
     // Create API client
     $this->_clientInstance = new WordpressClient($this->endpoint, $this->username, $this->password);
     $this->_clientInstance->setProxy($this->proxyConfig);
     $this->_clientInstance->setAuth($this->httpAuthConfig);
 }
コード例 #9
0
 public function fieldTypeValidation()
 {
     // Messages
     $invalidMessage = "the input value has a not valid value.";
     // Validation by Input Type
     foreach ($this->fields as $field) {
         foreach ($field as $key => $value) {
             // Text
             if ($key === "type" && $value === "text") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Tel
             if ($key === "type" && $value === "tel") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     } else {
                         // By default, the number must be a international phone number
                         $phoneValidator = new PhoneValidator();
                         if (!$phoneValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error . ' ' . Yii::t("app", "It must has a internationally-standardized format\n                                (e.g. '+1 650-555-5555')"));
                         }
                     }
                 }
             }
             // Url
             if ($key === "type" && $value === "url") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config validator
                     $config = [];
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $config['pattern'] = $field["pattern"];
                     }
                     $urlValidator = new UrlValidator($config);
                     if (!$urlValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // Color
             if ($key === "type" && $value === "color") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // hex color invalid
                     if (!preg_match('/^#[a-f0-9]{6}$/i', $this->data[$field["name"]])) {
                         $this->addError($field["name"], $field["label"], '', $invalidMessage . ' ' . Yii::t("app", "It must be a hexadecimal color string (e.g. '#FFFFFF')."));
                     }
                 }
             }
             // Password
             if ($key === "type" && $value === "password") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     $newData = trim($this->data[$field["name"]]);
                     // Remove spaces
                     $stringValidator = new StringValidator(['min' => 6]);
                     if (!$stringValidator->validate($newData, $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $regexValidator = new RegularExpressionValidator(['pattern' => $field["pattern"]]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Email
             if ($key === "type" && $value === "email") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config email validator
                     $config = [];
                     // A pattern can be used
                     if (isset($field["pattern"])) {
                         $config['pattern'] = $field["pattern"];
                     }
                     // Whether to check if email's domain exists and has either an A or MX record.
                     // Be aware that this check can fail due temporary DNS problems
                     // even if the email address is valid and an email would be deliverable
                     if (isset($field["data-check-dns"])) {
                         $config['checkDNS'] = true;
                     }
                     // Validate multiple emails separated by commas
                     if (isset($field["multiple"])) {
                         // Removes spaces
                         $emails = str_replace(" ", "", $this->data[$field["name"]]);
                         // Array of emails
                         $emails = explode(",", $emails);
                         if (count($emails) > 1) {
                             $config['message'] = Yii::t('app', '{attribute} has a invalid email format: Please use a comma to separate multiple email addresses.');
                         }
                         // Validate only one email address
                         $emailValidator = new EmailValidator($config);
                         foreach ($emails as $email) {
                             if (!$emailValidator->validate($email, $error)) {
                                 $this->addError($field["name"], $field["label"], '', $error);
                             }
                         }
                     } else {
                         // Validate only one email address
                         $emailValidator = new EmailValidator($config);
                         if (!$emailValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                     }
                 }
             }
             // Radio
             if ($key === "type" && $value === "radio") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no values or if the received data does not match with the form data
                     if (empty($this->radioValues) || !in_array($this->data[$field["name"]], $this->radioValues)) {
                         $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage);
                     }
                 }
             }
             // Checkbox
             if ($key === "type" && $value === "checkbox") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no values or if the received data does not match with the form data
                     foreach ($this->data[$field["name"]] as $labelChecked) {
                         if (empty($this->checkboxValues) || !in_array($labelChecked, $this->checkboxValues)) {
                             $this->addError($field["name"], $field["groupLabel"], '', $invalidMessage);
                         }
                     }
                 }
             }
             // Select List
             if ($key === "tagName" && $value === "select") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && !empty($this->data[$field["name"]])) {
                     // If no labels or if the received data does not match with the form data
                     foreach ($this->data[$field["name"]] as $optionSelected) {
                         if (empty($this->optionValues) || !in_array($optionSelected, $this->optionValues)) {
                             $this->addError($field["name"], $field["label"], '', $invalidMessage);
                         }
                     }
                 }
             }
             // Number & Range
             if ($key === "type" && $value === "number" || $key === "type" && $value === "range") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // Config number validator
                     $config = [];
                     // Min Number Validation (Minimum value required)
                     if (isset($field["min"])) {
                         $config['min'] = $field["min"];
                     }
                     // Max Number Validation (Maximum value required)
                     if (isset($field["max"])) {
                         $config['max'] = $field["max"];
                     }
                     // Only Integer Validation (Whether the attribute value can only be an integer)
                     if (isset($field["data-integer-only"])) {
                         $config['integerOnly'] = true;
                     }
                     // Pattern to Validate only Integer Numbers (The regular expression for matching integers)
                     if (isset($field["data-integer-pattern"])) {
                         $config['integerPattern'] = $field["data-integer-pattern"];
                     }
                     // Pattern to Validate the Number (The regular expression for matching numbers)
                     if (isset($field["data-number-pattern"])) {
                         $config['numberPattern'] = $field["data-number-pattern"];
                     }
                     $numberValidator = new NumberValidator($config);
                     if (!$numberValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // Date & DateTime & Time & Month & Week
             if ($key === "type" && $value === "date" || $key === "type" && $value === "datetime-local" || $key === "type" && $value === "time" || $key === "type" && $value === "month" || $key === "type" && $value === "week") {
                 // Only when the input value is not empty
                 if (isset($field["name"]) && trim($this->data[$field["name"]]) !== "") {
                     // DateValidator Configuration array
                     $config = [];
                     // Date Format by default
                     $format = "Y-m-d";
                     // Change Format
                     if ($value === "datetime-local") {
                         // DateTime Format
                         $format = "Y-m-d\\TH:i:s";
                     } elseif ($value === "time") {
                         // Time Format
                         $format = "i:s";
                     } elseif ($value === "month") {
                         // Month Format
                         $format = "Y-m";
                     } elseif ($value === "week") {
                         // First, validate by regular expression
                         $regexValidator = new RegularExpressionValidator(['pattern' => "/\\d{4}-W\\d{2}/"]);
                         if (!$regexValidator->validate($this->data[$field["name"]], $error)) {
                             $this->addError($field["name"], $field["label"], '', $error);
                         }
                         // Next, convert to date, to dateValidator (min / max)
                         if (isset($field["min"])) {
                             $config['tooSmall'] = Yii::t("app", "{attribute} must be no less than {weekMin}.", ['weekMin' => $field["min"]]);
                             $field["min"] = date("Y-m-d", strtotime($field["min"]));
                         }
                         if (isset($field["max"])) {
                             $config['tooBig'] = Yii::t("app", "{attribute} must be no greater than {weekMax}.", ['weekMax' => $field["max"]]);
                             $field["max"] = date("Y-m-d", strtotime($field["max"]));
                         }
                         $this->data[$field["name"]] = date("Y-m-d", strtotime($this->data[$field["name"]]));
                     }
                     // Add PHP format
                     $config['format'] = "php:" . $format;
                     // Add Min Date Validation (The value must be later than this option)
                     if (isset($field["min"])) {
                         $config['min'] = $field["min"];
                     }
                     // Add Max Date Validation (The value must be earlier than this option)
                     if (isset($field["max"])) {
                         $config['max'] = $field["max"];
                     }
                     $dateValidator = new DateValidator($config);
                     if (!$dateValidator->validate($this->data[$field["name"]], $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
             // File
             if ($key === "type" && $value === "file") {
                 // Only when the $_FILES name value is not empty
                 if (isset($field["name"]) && isset($_FILES[$field["name"]]['name']) && !empty($_FILES[$field["name"]]['name'])) {
                     // Config FileValidator
                     $config = [];
                     // File type validation
                     // Note that you should enable fileinfo PHP extension.
                     if (isset($field["accept"]) && extension_loaded('fileinfo')) {
                         // Removes dots
                         $extensions = str_replace(".", "", $field["accept"]);
                         // Removes spaces
                         $extensions = str_replace(" ", "", $extensions);
                         $config['extensions'] = explode(",", $extensions);
                     }
                     // File Min Size validation
                     if (isset($field["data-min-size"])) {
                         // Removes dots
                         $config['minSize'] = (int) $field["data-min-size"];
                     }
                     // File Min Size validation
                     if (isset($field["data-max-size"])) {
                         // Removes dots
                         $config['maxSize'] = (int) $field["data-max-size"];
                     }
                     $file = UploadedFile::getInstanceByName($field["name"]);
                     $fileValidator = new FileValidator($config);
                     if (!$fileValidator->validate($file, $error)) {
                         $this->addError($field["name"], $field["label"], '', $error);
                     }
                 }
             }
         }
     }
 }
コード例 #10
0
ファイル: Acme.php プロジェクト: sam002/yii2-acme
 /**
  * @throws InvalidConfigException
  */
 private function checkProviderUrl()
 {
     $validator = new UrlValidator();
     if (!$validator->validate($this->providerUrl)) {
         throw new InvalidConfigException($validator->message);
     }
     unset($validator);
 }
コード例 #11
0
ファイル: AcmeController.php プロジェクト: sam002/yii2-acme
 /**
  * Set domains
  * @param array $domains
  * @return array
  */
 private function domainsSet($domains = [])
 {
     if (empty($domains) || $this->confirm("Edit the list of domains?", false)) {
         //force get available domains
         $domainsSearched = array_filter(Yii::$aliases, function ($data, $key) {
             return is_string($key) && filter_var($data, FILTER_VALIDATE_URL);
         }, ARRAY_FILTER_USE_BOTH);
         if (empty($domains)) {
             $domains = ['manual' => 'manual set'];
         }
         //validate prompt as URL
         $urlValidation = function ($input, &$error) use($domains) {
             if (in_array($input, $domains)) {
                 $error = "Always set";
                 return false;
             }
             $urlValidator = new UrlValidator();
             $urlValidator->defaultScheme = 'http';
             $result = $urlValidator->validate($input, $error);
             unset($urlValidator);
             return $result;
         };
         $checked = $this->select("Select main domain:", array_merge($domainsSearched, $domains));
         $domains = [];
         $domains[] = $checked == 'manual' ? $this->prompt("Set domain:", ['validator' => $urlValidation]) : $checked;
         while ($this->confirm("Do need to add a domain?", false)) {
             $domains[] = $this->prompt("Set additional domain (type 'done' for cancel):", ['validator' => $urlValidation]);
         }
     }
     return $domains;
 }
コード例 #12
0
 protected function PrepareUrl($URLstr = false, $mask = false, $date = null)
 {
     $urlValidator = new UrlValidator();
     if (!$urlValidator->validate($URLstr)) {
         $URLstr = $this->OutSourceCNF['URL'];
     }
     if ($mask === false) {
         $mask = $this->OutSourceCNF['DateMask'];
     }
     if ($date === null) {
         $date = $this->UserDate;
     }
     $this->outURL = str_replace($mask, $date, $URLstr);
     return true;
 }
コード例 #13
0
ファイル: Config.php プロジェクト: skoro/yii2-admin-template
 /**
  * Validate 'value' attribute against of 'value_type'.
  */
 public function validateValue($attribute, $params = [])
 {
     if ($this->required) {
         $required = Yii::createObject(['class' => \yii\validators\RequiredValidator::className(), 'message' => Yii::t('app', '{label} is required.', ['label' => $this->title])]);
         if (!$required->validate($this->{$attribute})) {
             $this->addError($attribute, $required->message);
             return;
         }
     } else {
         $value = $this->{$attribute};
         if ($value === null || $value === '') {
             return;
         }
     }
     switch ($this->value_type) {
         case static::TYPE_INT:
             $args = ['class' => NumberValidator::className(), 'integerOnly' => true, 'message' => 'Not an integer'];
             break;
         case static::TYPE_NUM:
             $args = ['class' => NumberValidator::className(), 'message' => 'Not a number'];
             break;
         case static::TYPE_EMAIL:
             $args = ['class' => EmailValidator::className(), 'message' => 'Not a valid email'];
             break;
         case static::TYPE_URL:
             $args = ['class' => UrlValidator::className(), 'message' => 'Not a valid url'];
             break;
         case static::TYPE_SWITCH:
             $args = ['class' => BooleanValidator::className(), 'message' => 'Must be boolean value'];
             break;
         case static::TYPE_TEXT:
         case static::TYPE_EDITOR:
         case static::TYPE_PASSWORD:
             $args = ['class' => StringValidator::className()];
             break;
         case static::TYPE_SELECT:
             $args = ['class' => RangeValidator::className(), 'range' => array_keys($this->options), 'message' => 'Invalid value'];
             break;
         default:
             throw new InvalidParamException('Unknown config type: ' . $this->value_type);
     }
     $validator = Yii::createObject($args);
     if (!$validator->validate($this->{$attribute})) {
         $this->addError($attribute, $validator->message);
     } else {
         $this->castType();
     }
 }