It can also parse internationalized dates in a specific [[locale]] like e.g. 12 мая 2014 when [[format]] is configured to use a time pattern in ICU format. It is further possible to limit the date within a certain range using [[min]] and [[max]]. Additional to validating the date it can also export the parsed timestamp as a machine readable format which can be configured using [[timestampAttribute]]. For values that include time information (not date-only values) also the time zone will be adjusted. The time zone of the input value is assumed to be the one specified by the [[timeZone]] property and the target timeZone will be UTC when [[timestampAttributeFormat]] is null (exporting as UNIX timestamp) or [[timestampAttributeTimeZone]] otherwise. If you want to avoid the time zone conversion, make sure that [[timeZone]] and [[timestampAttributeTimeZone]] are the same.
부터: 2.0
저자: Qiang Xue (qiang.xue@gmail.com)
저자: Carsten Brandt (mail@cebe.cc)
상속: extends Validator
예제 #1
0
 public function testValidateAttribute()
 {
     // error-array-add
     $val = new DateValidator();
     $model = new FakedValidationModel();
     $model->attr_date = '2013-09-13';
     $val->validateAttribute($model, 'attr_date');
     $this->assertFalse($model->hasErrors('attr_date'));
     $model = new FakedValidationModel();
     $model->attr_date = '1375293913';
     $val->validateAttribute($model, 'attr_date');
     $this->assertTrue($model->hasErrors('attr_date'));
     //// timestamp attribute
     $val = new DateValidator(['timestampAttribute' => 'attr_timestamp']);
     $model = new FakedValidationModel();
     $model->attr_date = '2013-09-13';
     $model->attr_timestamp = true;
     $val->validateAttribute($model, 'attr_date');
     $this->assertFalse($model->hasErrors('attr_date'));
     $this->assertFalse($model->hasErrors('attr_timestamp'));
     $this->assertEquals(DateTime::createFromFormat($val->format, '2013-09-13')->getTimestamp(), $model->attr_timestamp);
     $val = new DateValidator();
     $model = FakedValidationModel::createWithAttributes(['attr_date' => []]);
     $val->validateAttribute($model, 'attr_date');
     $this->assertTrue($model->hasErrors('attr_date'));
 }
예제 #2
0
 public function validateAttribute($model, $attribute)
 {
     $error = false;
     $dateValidator = new DateValidator();
     if (preg_match("/([0-9]{2}[\\/|\\.]{1}[0-9]{2}[\\/|\\.]{1}[0-9]{4}) ([0-9]{2}:[0-9]{2})/", $model->{$attribute}, $mm)) {
         if (!$dateValidator->validateValue($mm[1]) || !RadiataHelper::validateTime($mm[2])) {
             $error = true;
         }
     } else {
         $error = true;
     }
     if ($error) {
         $this->addError($model, $attribute, Yii::t('b/radiata/forms', 'DateTime format error'));
     }
 }
예제 #3
0
 public function getData($date = null)
 {
     $dateValidator = new DateValidator();
     $dateValidator->format = Yii::$app->params['DateFormat'];
     $getDT = CurrencyData::find()->select(['letter_code', 'currencyRU', 'currencyUA']);
     if ($date !== null && !empty($date) && $dateValidator->validate($date)) {
         $getDT->where(['source_date' => Yii::$app->formatter->asDate($date, Yii::$app->params['DbFormat'])]);
     }
     $allDataArr = $getDT->asArray()->all();
     if (empty($allDataArr) && $date !== null && !empty($date)) {
         return [];
     }
     return $allDataArr;
     #return array[data] || empty array[]
 }
예제 #4
0
 /**
  * @inheritdoc
  */
 protected function parseDateValue($value)
 {
     if ($this->isInDbFormat($value)) {
         return strtotime($value);
     }
     return parent::parseDateValue($value);
 }
예제 #5
0
 /**
  * @inheritdoc
  */
 protected function parseDateValue($value)
 {
     if ($value instanceof UTCDateTime) {
         return (int) $value->__toString();
     }
     return parent::parseDateValue($value);
 }
예제 #6
0
 /**
  * @inheritdoc
  */
 protected function parseDateValue($value)
 {
     if ($value instanceof UTCDateTime) {
         return $value->toDateTime()->getTimestamp();
     }
     return parent::parseDateValue($value);
 }
 /**
  * @inheritdoc
  */
 protected function parseDateValue($value)
 {
     if ($value instanceof \MongoDate) {
         return $value->sec;
     }
     return parent::parseDateValue($value);
 }
예제 #8
0
 /**
  * @inheritdoc
  */
 protected function parseDateValue($value)
 {
     if ($value instanceof \MongoDB\BSON\UTCDatetime) {
         /** @var \DateTime $datetime */
         $datetime = $value->toDateTime();
         return $datetime->format('U');
     }
     return parent::parseDateValue($value);
 }
예제 #9
0
 public function getData($date = null)
 {
     $dateValidator = new DateValidator();
     $dateValidator->format = Yii::$app->params['DateFormat'];
     $getDT = CurrencyData::find();
     if ($date !== null && !empty($date) && $dateValidator->validate($date)) {
         $getDT->where(['source_date' => Yii::$app->formatter->asDate($date, Yii::$app->params['DbFormat'])]);
     }
     $allDataArr = $getDT->asArray()->all();
     //new FullUpdater($date);
     if (empty($allDataArr) && $date !== null && !empty($date)) {
         new FullUpdater($date);
         // 'do update'
         return $this->getData($date);
     }
     return $allDataArr;
     #return array[data] || empty array[]
 }
예제 #10
0
 public function init()
 {
     if ($this->timestampAttributeFormat === null) {
         $this->timestampAttributeFormat = 'yyyy-MM-dd';
     }
     if ($this->timestampAttribute === null) {
         $this->timestampAttribute = $this->sqlAttribute;
     }
     parent::init();
 }
예제 #11
0
 /**
  * 
  * @param type $model
  * @param type $attribute
  */
 public function validateAttribute($model, $attribute)
 {
     parent::validateAttribute($model, $attribute);
     $errors = $model->getErrors($attribute);
     $value = $model->{$attribute};
     if (empty($errors) and !empty($value)) {
         $value = \DateTime::createFromFormat('d.m.Y', $value);
         $model->{$attribute} = $value;
     }
 }
예제 #12
0
 public function actionTest()
 {
     echo "<pre>";
     //Yii::$app->formatter->dateFormat = "php:Y-m-d";
     Func::print_br(Yii::$app->formatter->dateFormat);
     $validate = new DateValidator();
     $testVal = '2015.02.28';
     if ($validate->validate($testVal, $error)) {
         echo "{$testVal} 是有效日期!";
         echo Yii::$app->formatter->asDatetime(date('Y-m-d'));
     } else {
         Func::print_br($error);
     }
     /*$arr  = ['name', 'email'];
       $arr1 = [['name', 'email'], 'string', 'max'=>123];
       $arr2 = [['email'], 'email'];
       $result = compact('name', 'email', [[['name', 'email'], 'string', 'max'=>123], [['email'], 'email']]);
       VarDumper::dump($result);*/
     echo "</pre>";
 }
예제 #13
0
 protected function parseDateValue($value)
 {
     if ($value instanceof \MongoDate) {
         return $value;
     }
     $ts = parent::parseDateValue($value);
     if (!$ts) {
         return false;
     }
     if ($this->cast) {
         return new \MongoDate($ts);
     } else {
         return $ts;
     }
 }
 /**
  * @inheritdoc
  */
 public function init()
 {
     if ($this->format === null) {
         switch ($this->type) {
             case 'date':
                 $this->format = Yii::$app->formatter->dateFormat;
                 break;
             case 'time':
                 $this->format = Yii::$app->formatter->timeFormat;
                 break;
             case 'datetime':
                 $this->format = Yii::$app->formatter->datetimeFormat;
                 break;
         }
     }
     // if $this->format is a short format,
     // convert it to a pattern, so that DateValidator will respect $this->type.
     $this->format = FormatConverter::convertIcuShortFormatToPattern($this->format, $this->type, $this->locale);
     parent::init();
 }
 /**
  * Performs validation for all the attributes
  * @param Event $event
  */
 public function onBeforeValidate($event)
 {
     foreach ($this->attributeValues as $name => $value) {
         $options = ArrayHelper::merge(['class' => DateValidator::className(), 'format' => $value->localFormat[1]], $this->validatorOptions);
         $validator = Yii::createObject($options);
         $validator->validateAttributes($this->owner, [$value->localAttribute]);
     }
 }
예제 #16
0
 public function testValidateAttributeICUFormat()
 {
     // error-array-add
     $val = new DateValidator(['format' => 'yyyy-MM-dd']);
     $model = new FakedValidationModel();
     $model->attr_date = '2013-09-13';
     $val->validateAttribute($model, 'attr_date');
     $this->assertFalse($model->hasErrors('attr_date'));
     $model = new FakedValidationModel();
     $model->attr_date = '1375293913';
     $val->validateAttribute($model, 'attr_date');
     $this->assertTrue($model->hasErrors('attr_date'));
     //// timestamp attribute
     $val = new DateValidator(['format' => 'yyyy-MM-dd', 'timestampAttribute' => 'attr_timestamp']);
     $model = new FakedValidationModel();
     $model->attr_date = '2013-09-13';
     $model->attr_timestamp = true;
     $val->validateAttribute($model, 'attr_date');
     $this->assertFalse($model->hasErrors('attr_date'));
     $this->assertFalse($model->hasErrors('attr_timestamp'));
     $this->assertEquals(mktime(0, 0, 0, 9, 13, 2013), $model->attr_timestamp);
     $val = new DateValidator(['format' => 'yyyy-MM-dd']);
     $model = FakedValidationModel::createWithAttributes(['attr_date' => []]);
     $val->validateAttribute($model, 'attr_date');
     $this->assertTrue($model->hasErrors('attr_date'));
 }
예제 #17
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);
                     }
                 }
             }
         }
     }
 }
예제 #18
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return [[['userUid'], 'string', 'length' => 36], [['firstName', 'lastName'], 'string', 'max' => 255], ['birthday', DateValidator::className(), 'format' => 'dd.MM.yyyy'], ['phone', PhoneValidator::className()]];
 }
예제 #19
0
 /**
  * Performs validation for all the attributes
  * @param Event $event
  */
 public function onBeforeValidate($event)
 {
     foreach ($this->attributeValues as $targetAttribute => $value) {
         if ($value instanceof DateTimeAttribute) {
             $validator = \Yii::createObject(['class' => DateValidator::className(), 'format' => self::normalizeIcuFormat($value->targetFormat, $this->formatter)[1]]);
             $validator->validateAttribute($this->owner, $targetAttribute);
         }
     }
 }
 public function testIntlMultibyteString()
 {
     $val = new DateValidator(['format' => 'dd MMM yyyy', 'locale' => 'de_DE']);
     $model = FakedValidationModel::createWithAttributes(['attr_date' => '12 Mai 2014']);
     $val->validateAttribute($model, 'attr_date');
     $this->assertFalse($model->hasErrors('attr_date'));
     $val = new DateValidator(['format' => 'dd MMM yyyy', 'locale' => 'ru_RU']);
     $model = FakedValidationModel::createWithAttributes(['attr_date' => '12 мая 2014']);
     $val->validateAttribute($model, 'attr_date');
     $this->assertFalse($model->hasErrors('attr_date'));
 }
예제 #21
0
 public function testIntlValidateValueRangeOld()
 {
     if ($this->checkOldIcuBug()) {
         $this->markTestSkipped("ICU is too old.");
     }
     $date = '14-09-13';
     $val = new DateValidator(['format' => 'yyyy-MM-dd', 'min' => '1900-01-01']);
     $this->assertFalse($val->validate($date), "{$date} is too small");
 }