public function testValidatorWithFilterGroups() { $allOfFilter = new AllOfFilter([new ClosureFilter('name', v::intVal()), v::key('key', v::regex('/test.+/i'))]); static::assertTrue($allOfFilter->matches(['name' => '1234', 'key' => 'test47382'])); static::assertFalse($allOfFilter->matches(['name' => 'test', 'key' => 'test47382'])); static::assertFalse($allOfFilter->matches(['name' => '1234', 'key' => 'test'])); }
/** * @inheritDoc */ public static function isNiceString($string) { if (Validator::regex('/(\\w\\w).*\\1+/')->validate($string) && Validator::regex('/(\\w)\\w\\1/')->validate($string)) { return true; } return false; }
/** * @param string $table * @param \Closure $closure * @return bool */ public function table($table, \Closure $closure) { Validator::type('string')->assert($table); Validator::regex('/^[A-Za-z_]+$/')->assert($table); /** @var Schema $schema */ $schema = new $this->schemaClassName(); $closure($schema); $writer = new SchemaWriter($table, $schema); return $writer->write($this->overwrite); }
/** * An invalid amount gets automatically turned into 0 when you set it, so we need to validate seperately */ public function validateAmount($amount) { // Check the Amount is a valid format if (!v::regex('/^[0-9,]+(\\.[0-9]{1,2})?$/')->validate($amount)) { $this->addError('Amount', $this->AMOUNT_BAD_FORMAT); } else { if (v::regex('/,[0-9]{2}$/')->validate($amount)) { // Detect possible use of comma as decimal delimiter $this->addError('Amount', $this->AMOUNT_BAD_FORMAT); } } // Strip the Amount of commas so we can play with it as a number $amount = str_replace(',', '', $amount); // Lets work in pennies, because then we can't get confused with floats $amount = $amount * 100; if ($amount < 1 || $amount > 10000000) { $this->addError('Amount', $this->AMOUNT_BAD_RANGE); } return $this; }
/** * 检查输入是否符合正则 * * @param string $value 要检查的值 * @param string $expression 正则表达式(包含分隔符) * @return bool */ public static function regex($value, $expression) { return Validator::regex($expression)->validate($value); }
private function assertName($name) { Validator::notEmpty()->assert($name); Validator::type('string')->assert($name); Validator::regex('/^[A-Za-z_]+$/')->assert($name); }
<?php /** * Created by PhpStorm. * User: who * Date: 5/11/16 * Time: 1:13 PM */ require "../vendor/autoload.php"; use Respect\Validation\Validator as v; $number = '123456a'; $res = v::numeric()->validate($number); try { v::regex('/^[\\x{4e00}-\\x{9fa5}]{1,32}$/u')->setName('金额')->check('汉字d'); } catch (\Respect\Validation\Exceptions\ValidationException $exception) { echo $exception->getMainMessage(); }
/** * Validates that input matches a regex * * @param string $hook "validate:regex" * @param string $type "prototyper" * @param ValidationStatus $validation Current validation status * @param array $params Hook params * @return ValidationStatus */ function prototyper_validate_regex($hook, $type, $validation, $params) { if (!$validation instanceof ValidationStatus) { $validation = new ValidationStatus(); } $field = elgg_extract('field', $params); if (!$field instanceof Field) { return $validation; } $rule = elgg_extract('rule', $params); if ($rule != "regex") { return $validation; } $value = elgg_extract('value', $params); $expectation = elgg_extract('expectation', $params); if (!v::regex($expectation)->validate($value)) { $validation->setFail(elgg_echo('prototyper:validate:error:regex', array($field->getLabel(), $expectation))); } return $validation; }
/** * 创建用户 * * @param string $username * @param string $password * @param string $email * @return int UID * @throws InvalidArgumentException * @throws UserException */ public function createUser($username, $password, $email) { if (!is_string($username)) { throw new InvalidArgumentException('username', 'type_invalid'); } if (!is_string($password)) { throw new InvalidArgumentException('password', 'type_invalid'); } if (!is_string($email)) { throw new InvalidArgumentException('email', 'type_invalid'); } // 检查用户名 if (!mb_check_encoding($username, 'UTF-8')) { throw new InvalidArgumentException('username', 'encoding_invalid'); } $username = trim($username); if (!Validator::regex('/^\\S*$/')->length(3, 16)->validate($username)) { throw new InvalidArgumentException('username', 'format_invalid'); } // 检查关键字 $keyword = KeywordFilter::isContainGeneric($username); if ($keyword === false) { $keyword = KeywordFilter::isContainName($username); } if ($keyword !== false) { throw new UserException('UserManager.name_forbid', ['keyword' => $keyword]); } // 检查密码 if (!Validator::length(0, 50)->validate($password)) { throw new InvalidArgumentException('password', 'format_invalid'); } // 检查 email if (!Validator::email()->validate($email)) { throw new InvalidArgumentException('password', 'format_invalid'); } // 处理用户名 $username = VJ::removeEmoji($username); // 检查用户名和 Email 是否唯一 if (UserUtil::getUserObjectByUsername($username) !== null) { throw new UserException('UserManager.createUser.user_exists'); } if (UserUtil::getUserObjectByEmail($email) !== null) { throw new UserException('UserManager.createUser.email_exists'); } // 生成 hash & salt $hashSaltPair = $this->user_credential->password_encoder->generateHash($password); // 插入记录 try { $_id = new \MongoId(); $doc = ['_id' => $_id, 'uid' => $_id, 'user' => $username, 'luser' => UserUtil::canonicalizeUsername($username), 'mail' => $email, 'lmail' => UserUtil::canonicalizeEmail($email), 'salt' => $hashSaltPair['salt'], 'hash' => $hashSaltPair['hash'], 'g' => $email, 'gender' => VJ::USER_GENDER_UNKNOWN, 'regat' => new \MongoDate(), 'regip' => $this->request->getClientIp()]; Application::coll('User')->insert($doc); } catch (\MongoCursorException $e) { // 插入失败 throw new UserException('UserManager.createUser.user_or_email_exists'); } // 插入成功:更新 uid // 获取递增 uid $counterRec = Application::coll('System')->findAndModify(['_id' => 'UserCounter'], ['$inc' => ['count' => 1]], [], ['new' => true, 'upsert' => true]); $uid = (int) $counterRec['count']; try { // 修改 uid Application::coll('User')->update(['_id' => $_id], ['$set' => ['uid' => $uid]]); } catch (\MongoCursorException $e) { // 修改 uid 失败(uid 重复),则删除用户记录 Application::critical('createUser.uidDuplicate', ['uid' => $uid]); Application::coll('User')->remove(['_id' => $_id], ['justOne' => true]); throw new UserException('UserManager.createUser.internal'); } Application::emit('user.created', [$uid]); return $uid; }
public function validate($item) { $metaData = Transaction::get('array'); foreach ($this->fieldsToCheck as $field) { if (is_a($this, 'Academe\\SagePay\\Validator\\Model\\Address')) { // I'm assuming/hoping that Billing and Delivery validation rules are identical $data = $metaData['Billing' . $field]; } else { $data = $metaData[$field]; } $value = $item->getField($field); if ($this->hasError($field)) { // We only store one error per field, so if we have already got an error for this // field then don't waste time checking others. This also means that we can have // more specific fields in the child objects which over-ride these completly. continue; } // State is only used when the country is US, the validation rules stores assume country is US. // so here we tweak them. if ($field == 'State' && $item->getField('Country') != 'US') { $data['required'] = false; $data['min'] = 0; $data['max'] = 0; } // If the item is required, check it's not empty if ($data['required'] && !v::notEmpty()->validate($value)) { if ($field == 'PostCode') { // Add an exception for Postcodes when the country is one which does not have postcodes if (!in_array($item->getField('Country'), $this->countriesWhichDontHavePostcodes)) { $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field)); } } else { if ($field == 'Amount') { // 0 equates to empty, so do a special check if ($item->getField('Amount') != '0' && !v::string()->notEmpty()->validate($item->getField('Amount'))) { $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field)); } } else { $this->addError($field, sprintf($this->CANNOT_BE_EMPTY, $field)); } } } // If there is a minimum or maximum check the length. // TODO: Check whether this code works well when only one or the other is set $min = isset($data['min']) ? $data['min'] : null; $max = isset($data['max']) ? $data['max'] : null; if ($min != null && $max != null) { // Check the length of the field if ($field == 'State') { print_r("\n\nMin: {$field} : {$min}, \n\n"); die; } if (!v::length($min, $max, true)->validate($value)) { if ($min == $max) { $this->addError($field, sprintf($this->BAD_LENGTH, $field, $min)); } else { $this->addError($field, sprintf($this->BAD_RANGE, $field, $min, $max)); } } } // Check the contents of the field if (isset($data['chars'])) { // We build two regexes, one for testing whether it matches and the other for // filtering out the bad characters to show the user which are not valid. $regex = $this->buildRegex($data['chars']); try { if (!v::regex($regex)->validate($value)) { $cleanupRegex = $this->buildRegex($data['chars'], false); $badChars = preg_replace($cleanupRegex, '', $value); $this->addError($field, sprintf($this->BAD_CHARACTERS, $field, $badChars, $regex)); } } catch (\Exception $e) { throw new \Exception("preg_match has a problem with this regex '{$regex}'"); } } } return $this; }