Note, this validator should only be used with string-typed attributes.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends Validator
Exemplo n.º 1
0
 /**
  * Add Original Text
  * @param string $text
  * @param int $yandexSiteID
  * @throws InvalidParamException
  * @return string|bool
  */
 public function addOriginalText($text, $yandexSiteID)
 {
     /** @var Cache $cache */
     $cache = \Yii::$app->get($this->cacheComponent);
     $cacheKey = "Yandex_OT_sent:" . $this->clientID . "_" . $this->clientSecret;
     $sent = $cache->get($cacheKey);
     if ($sent === false) {
         $sent = 0;
     }
     if ($sent >= self::YANDEX_OT_DAILY_LIMIT) {
         throw new InvalidParamException("Daily limit exceeded!");
     }
     $validator = new StringValidator(['min' => self::YANDEX_OT_MIN, 'max' => self::YANDEX_OT_MAX, 'enableClientValidation' => false]);
     if (!$validator->validate($text, $error)) {
         throw new InvalidParamException($error);
     }
     $text = urlencode(htmlspecialchars($text));
     $text = "<original-text><content>{$text}</content></original-text>";
     $response = $this->apiClient->rawApi("hosts/{$yandexSiteID}/original-texts/", "POST", $text);
     $success = ArrayHelper::keyExists('id', $response) && ArrayHelper::keyExists('link', $response);
     if ($success) {
         $sent++;
         $cache->set($cacheKey, $sent, 60 * 60 * 24);
     }
     return $success;
 }
Exemplo n.º 2
0
 /**
  * @param $attribute
  */
 public function validatePassword($attribute)
 {
     if (empty($this->password)) {
         return;
     }
     $StringValidator = new StringValidator(['min' => 6]);
     $StringValidator->validateAttribute($this, 'password');
     $CompareValidator = new CompareValidator(['compareAttribute' => 'password']);
     $CompareValidator->validateAttribute($this, 'repassword');
 }
Exemplo n.º 3
0
 public function init()
 {
     if ($this->message === null) {
         $this->message = \Yii::t('yii', '{attribute} must be a date.');
     }
     parent::init();
 }
Exemplo n.º 4
0
 /**
  * Updates the value of setting.
  * @param string[] $data
  * @return boolean
  */
 public function update($data)
 {
     $validator = new StringValidator();
     $validator->max = 255;
     foreach ($data as $key => $value) {
         if (!in_array($key, $this->readonly) && isset($this->settings[$key])) {
             if ($validator->validate($value)) {
                 if (!$this->config->set($key, $value)) {
                     return false;
                 }
             } else {
                 return false;
             }
         }
     }
     return true;
 }
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if ($this->pattern === null) {
         throw new InvalidConfigException('The "pattern" property must be set.');
     }
     if ($this->patternMessage === null) {
         $this->patternMessage = Yii::t('yii', '{attribute} is invalid.');
     }
 }
Exemplo n.º 6
0
 /**
  * @return array
  */
 public function rules()
 {
     return [['parent_id', 'validateParent'], ['label', StringValidator::className()], ['label', RequiredValidator::className()], ['path', StringValidator::className()], ['status', BooleanValidator::className()], ['order_num', NumberValidator::className()]];
 }
Exemplo n.º 7
0
 /**
  * Validates images assigned to the page.
  *
  * @param string $attribute the attribute currently being validated
  * @param mixed $params the value of the "params" given in the rule
  */
 public function validateImages($attribute, $params)
 {
     $validator = new StringValidator();
     foreach ($this->{$attribute} as $image) {
         if (!empty($image['image']) && !$validator->validate($image['image'], $error)) {
             $this->addError($attribute, Yii::t('cms', 'Image must be a string.'));
         }
     }
 }
Exemplo n.º 8
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);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 9
0
 public function rules()
 {
     return [[['type', 'name'], RequiredValidator::className()], [['length', 'precision', 'scale'], NumberValidator::className()], [['is_not_null', 'is_unique', 'unsigned', 'isCompositeKey'], BooleanValidator::className()], [['name'], StringValidator::className(), 'max' => 50], [['comment', 'fk_name'], StringValidator::className(), 'max' => 255], [['type'], RangeValidator::className(), 'range' => $this->getTypeList()]];
 }
Exemplo n.º 10
0
 public function rules()
 {
     return [['name', StringValidator::className()], ['slug', 'match', 'pattern' => self::$SLUG_PATTERN, 'message' => Yii::t('easyii', 'Slug can contain only 0-9, a-z and "-" characters (max: 128).')], ['slug', 'default', 'value' => null], ['slug', 'unique']];
 }
Exemplo n.º 11
0
 /**
  * @return User
  */
 private function createAdminUser()
 {
     $name = $this->prompt("Введите имя суперпользовтаеля системы", ['default' => 'admin']);
     $password = $this->prompt("Введите пароль суперпользователя системы:", ['required' => true, 'validator' => function ($input) {
         $validator = new StringValidator(['min' => 6]);
         return $validator->validate($input);
     }]);
     $user = new User();
     $user->username = $name;
     $user->setPassword($password);
     $user->status = User::STATUS_ACTIVE;
     $user->email = Yii::$app->params['email.admin'];
     $user->generateAuthKey();
     $user->save();
     return $user;
 }
Exemplo n.º 12
0
 public function testCustomErrorMessageInValidateAttribute()
 {
     $val = new StringValidator(['min' => 5, 'tooShort' => '{attribute} to short. Min is {min}']);
     $model = new FakedValidationModel();
     $model->attr_string = 'abc';
     $val->validateAttribute($model, 'attr_string');
     $this->assertTrue($model->hasErrors('attr_string'));
     $errorMsg = $model->getErrors('attr_string');
     $this->assertEquals('attr_string to short. Min is 5', $errorMsg[0]);
 }
Exemplo n.º 13
0
 /**
  * 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();
     }
 }
Exemplo n.º 14
0
 /**
  * validateAttribute
  * 
  * @param type $model
  * @param type $attribute
  * @return type
  */
 public function validateAttribute($model, $attribute)
 {
     $model->{$attribute} = (string) $model->{$attribute};
     return parent::validateAttribute($model, $attribute);
 }
Exemplo n.º 15
0
 /**
  * @return User
  */
 private function createAdminUser()
 {
     $password = $this->prompt("Введите пароль суперпользователя системы:", ['required' => true, 'validator' => function ($input) {
         $validator = new StringValidator(['min' => 6]);
         return $validator->validate($input);
     }]);
     $user = new User();
     $user->username = Yii::$app->params['admin.name'];
     $user->setPassword($password);
     $user->email = Yii::$app->params['admin.email'];
     $user->generateAuthKey();
     $user->save();
     return $user;
 }