/** * @param \yii\base\Model $model * @param string $attribute */ public function validateAttribute($model, $attribute) { $regexpValidator = new RegularExpressionValidator(['pattern' => '/^9[0-9]{9}$/']); if (!$regexpValidator->validate($model->{$attribute})) { $this->addError($model, $attribute, '{attribute} имеет неверный формат'); return; } $existValidator = new ExistValidator(['targetClass' => Number::className(), 'targetAttribute' => 'number']); if (!$existValidator->validate($model->{$attribute})) { $this->addError($model, $attribute, "{attribute} не существует"); } }
/** * @inheritdoc */ public function init() { if ($this->message === null) { $this->message = Yii::t('validator', 'A username can consist of alphabetic characters, numbers, dashes and underscores.'); } parent::init(); }
/** * @inheritdoc */ public function init() { if ($this->message === null) { $this->message = Yii::t('validator', "A name can consist of Latin alphabetic characters. It can contain points, apostrophes ['] and ordinals [ºª] as terminators of words, and blank spaces [ ] or dashes [-] as separator characters. A name can not contain more than one successive separator character."); } parent::init(); }
/** * @inheritdoc */ public function init() { $this->pattern = '/^[a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(([,.\'\\/ºª]{1}[\\s]?|[ºª]{1}[\\-]?|[\\s\\-]{1})[a-zA-ZÀ-ÖØ-öø-ÿ0-9]+)*\\.?$/u'; if ($this->message === null) { $this->message = Yii::t('validator', "An address can consist of Latin alphabetic characters. It can contain punctuation marks like points [.], commas [,], slashes [/] and apostrophes ['] followed by a blank space, ordinal [ºª] as terminator of word and blank spaces [ ] or dashes [-] as word separator characters. An address can't contain more than one successive separator character."); } parent::init(); }
/** * @inheritdoc */ public function init() { $this->pattern = '/^[a-zA-ZÀ-ÖØ-öø-ÿ]+(([.\'ªº]{1}[\\s]?|[\\s\\-]{1})[a-zA-ZÀ-ÖØ-öø-ÿ]+)*[.ªº]?$/u'; if ($this->message === null) { $this->message = Yii::t('validator', "A name can consist of Latin alphabetic characters. It can contain points, apostrophes ['] and ordinals [ºª] as terminators of words, and blank spaces [ ] or dashes [-] as separator characters. A name can not contain more than one successive separator character."); } parent::init(); }
public function clientValidateAttribute($model, $attribute, $view) { $js = parent::clientValidateAttribute($model, $attribute, $view); if (!$this->enableIdn) { return $js; } PunycodeAsset::register($view); return "value = punycode.toASCII(value); {$js}"; }
public function init() { if ($this->message === null) { $this->message = "«{attribute}» должен быть в формате {$this->mask}."; } $qFormat = preg_quote($this->mask, '/'); $this->pattern = '/^' . strtr($qFormat, ['9' => '\\d']) . '$/'; parent::init(); }
/** * {@inheritdoc} */ public function init() { parent::init(); $this->message = Yii::t('hipanel:dns', '{attribute} is not a valid domain name'); }
/** * @param \yii\base\Model $model the data model to be validated * @param string $attribute the name of the attribute to be validated. */ protected function validateCharacters($model, $attribute) { if ($this->characters) { $this->validatorCharacters->validateAttribute($model, $attribute); } }
/** * @inheritdoc */ public function init() { $this->pattern = '/^[a-zA-ZÀ-ÖØ-öø-ÿ]+(([.\'ªº]{1}[\\s]?|[\\s\\-]{1})[a-zA-ZÀ-ÖØ-öø-ÿ]+)*[.ªº]?$/u'; parent::init(); }
/** * @inheritdoc */ public function init() { $this->pattern = $this->twelvehour ? self::TWELVEHOUR_PATTERN : self::TWENTYFOURHOUR_PATTERN; parent::init(); }
protected function validate($field, $regex) { $validator = new RegularExpressionValidator(['pattern' => $regex]); if ($validator->validate($field, $error)) { return true; } else { $this->error[] = Yii::t('db_rbac', 'Значение "{field}" содержит не допустимые символы', ['field' => $field]); return false; } }
/** * @inheritdoc */ public function init() { parent::init(); $this->message = \Yii::t('validators', $this->message); }
/** @inheritdoc */ public function init() { $this->pattern = '#^[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}$#'; parent::init(); }
public function testInitException() { $this->setExpectedException('yii\\base\\InvalidConfigException'); $val = new RegularExpressionValidator(); $val->validate('abc'); }
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); } } } } } }
/** * @inheritdoc */ public function init() { $this->pattern = '/^[a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(([,.\'\\/ºª]{1}[\\s]?|[ºª]{1}[\\-]?|[\\s\\-]{1})[a-zA-ZÀ-ÖØ-öø-ÿ0-9]+)*\\.?$/u'; parent::init(); }
/** * @inheritdoc */ public function clientValidateAttribute($model, $attribute, $view) { $RegularExpressionValidator = new RegularExpressionValidator(['pattern' => $this->pattern, 'message' => $this->message]); return $RegularExpressionValidator->clientValidateAttribute($model, $attribute, $view); }
protected function internalValidateValue(&$value) { $result = parent::validateValue($value); if (empty($result)) { if ($this->allowNamespace) { $result = $this->validateNsSeparator($value, 0, $this->leadingNamespaceSeparator); } else { if (!$this->allowNamespace && !$model->hasErrors()) { if (strpos($model->{$attribute}, '\\') !== FALSE) { $result = ['Namespace may not be specified', null]; } } } } return $result; }