Пример #1
0
    private function validateAsNumber($model,$attribute){
        $validator = new NumberValidator();

        if(!$validator->validate($model->$attribute, $error)){
            $model->addError('username' ,'Must be a Valid Number');
        }
    }
Пример #2
0
 /**
  * Валидирует массивы с ИД на корректность данных и их количество.
  *
  * @param string $attribute the attribute currently being validated
  * @param array $params the additional name-value pairs given in the rule
  */
 public function validateCount($attribute, $params)
 {
     //echo'<pre>'; print_r($this->$attribute);echo'</pre>';//die;
     if (!$this->hasErrors()) {
         $dotaParams = DotaParams::loadParams();
         $slots_field = $this->getSlotsField($attribute, $this->draft_id);
         $slots_count = $dotaParams->{$slots_field};
         //echo'<pre>'; print_r($slots_count);echo'</pre>';//die;
         //echo'<pre>'; print_r($slots_field);echo'</pre>';//die;
         //echo'<pre>'; print_r($this->draft_id);echo'</pre>';//die;
         //echo'<pre>'; print_r($this->$attribute);echo'</pre>';//die;
         if (count($this->{$attribute}) != $slots_count) {
             $this->addError($attribute, Yii::t('app', 'FANTASY_RATE_SEND_ERROR_SLOTS'));
         }
         $NumberValidator = new NumberValidator();
         $NumberValidator->integerOnly = true;
         $attr_value = $this->{$attribute};
         foreach ($attr_value as $v) {
             if (!$NumberValidator->validate($v)) {
                 $this->addError($attribute, Yii::t('app', 'FANTASY_RATE_SEND_ERROR_INT'));
                 break;
             }
         }
     }
 }
Пример #3
0
 /**
  * @return array
  */
 public function rules()
 {
     return [['operatorId', 'exist', 'targetClass' => Operator::className(), 'targetAttribute' => '_id'], ['period', function ($attribute) {
         $monthValidator = new NumberValidator(['integerOnly' => true, 'min' => 1, 'max' => 12]);
         $yearValidator = new NumberValidator(['integerOnly' => true, 'min' => 2014]);
         if (!$monthValidator->validate($this->period['month']) || !$yearValidator->validate($this->period['year'])) {
             $this->addError($attribute, "«{attribute}» имеет неверный формат");
         }
     }]];
 }
Пример #4
0
 /**
  * Валидирует массивы с ИД на корректность данных и их количество.
  *
  * @param string $attribute the attribute currently being validated
  * @param array $params the additional name-value pairs given in the rule
  */
 public function validateCount($attribute, $params)
 {
     if (!$this->hasErrors()) {
         $game_params = PokerParams::loadParams();
         $slots_count = $game_params->players_slots;
         if (count($this->{$attribute}) != $slots_count) {
             $this->addError($attribute, Yii::t('app', 'FANTASY_RATE_SEND_ERROR_SLOTS'));
         }
         $NumberValidator = new NumberValidator();
         $NumberValidator->integerOnly = true;
         $attr_value = $this->{$attribute};
         foreach ($attr_value as $v) {
             if (!$NumberValidator->validate($v)) {
                 $this->addError($attribute, Yii::t('app', 'FANTASY_RATE_SEND_ERROR_INT'));
                 break;
             }
         }
     }
 }
Пример #5
0
 /**
  * Phone number validation
  *
  * @param $attribute
  */
 public function validatePhones($attribute)
 {
     $items = $this->{$attribute};
     if (!is_array($items)) {
         $items = [];
     }
     $multiple = true;
     if (!is_array($items)) {
         $multiple = false;
         $items = (array) $items;
     }
     foreach ($items as $index => $item) {
         $validator = new NumberValidator();
         $error = null;
         $validator->validate($item, $error);
         if (!empty($error)) {
             $key = $attribute . ($multiple ? '[' . $index . ']' : '');
             $this->addError($key, $error);
         }
     }
 }
Пример #6
0
 /**
  * validate official QQ
  * @return string
  */
 public function actionKefuQqValidate()
 {
     $model = new KefuQqValidateForm();
     $numberValid = new NumberValidator();
     if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
         if (!$numberValid->validate($model->qq)) {
             //$model->addError('qq','输入的QQ号码无效!');
             \Yii::$app->session->setFlash('error', '输入的QQ号码无效!');
             return $this->render('validate-qq', ['model' => $model]);
         }
         if ($model->validateQQ()) {
             //$model->addError('qq','此QQ号码为官方QQ号码,请放心!');
             \Yii::$app->session->setFlash('success', '此QQ号码为官方QQ号码,请放心!');
             return $this->render('validate-qq', ['model' => $model]);
         } else {
             //$model->addError('qq','该QQ不是官方QQ,请谨防上当受骗!');
             \Yii::$app->session->setFlash('error', '该QQ不是官方QQ,请谨防上当受骗!');
             return $this->render('validate-qq', ['model' => $model]);
         }
     }
     return $this->render('validate-qq', ['model' => $model]);
 }
Пример #7
0
 public function validateMatrix($attribute, $params)
 {
     if (!$this->hasErrors()) {
         $NumberValidator = new NumberValidator();
         $NumberValidator->integerOnly = false;
         //echo'<pre>';print_r($this->grid);echo'</pre>';die;
         for ($pos = 0; $pos < count($this->positions_key); $pos++) {
             $err = false;
             for ($usr = 0; $usr < count($this->users_key); $usr++) {
                 $v = $this->grid[$this->positions_key[$pos]][$this->users_key[$usr]];
                 if (!$NumberValidator->validate($v)) {
                     $this->addError($attribute, 'Значение должно быть числом');
                     $err = true;
                     break;
                 }
             }
             if ($err === true) {
                 break;
             }
         }
     }
 }
 public function run($id)
 {
     $validator = new NumberValidator();
     $validator->integerOnly = true;
     if (!$validator->validate($id, $error)) {
         throw new HttpException(500, $error);
     }
     $query = (new $this->treeModelName())->find();
     $nodes = [];
     if ($id == 0) {
         $nodes = $query->roots()->all();
     } else {
         $parent = $query->where(['id' => $id])->one();
         if ($parent === null) {
             throw new NotFoundHttpException(Yii::t('gtreetable', 'Position indicated by parent ID is not exists!'));
         }
         $nodes = $parent->children(1)->all();
     }
     $result = [];
     foreach ($nodes as $node) {
         $result[] = ['id' => $node->getPrimaryKey(), 'name' => $node->getName(), 'level' => $node->getDepth(), 'type' => $node->getType()];
     }
     echo Json::encode(['nodes' => $result]);
 }
Пример #9
0
 public function testValidateValueRange()
 {
     $val = new NumberValidator(['min' => -10, 'max' => 20]);
     $this->assertTrue($val->validate(0));
     $this->assertTrue($val->validate(-10));
     $this->assertFalse($val->validate(-11));
     $this->assertFalse($val->validate(21));
     $val = new NumberValidator(['min' => -10, 'max' => 20, 'integerOnly' => true]);
     $this->assertTrue($val->validate(0));
     $this->assertFalse($val->validate(-11));
     $this->assertFalse($val->validate(22));
     $this->assertFalse($val->validate('20e-1'));
 }
Пример #10
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);
                     }
                 }
             }
         }
     }
 }