php Respect-Validation-Validator类(方法)实例源码

下面列出了php Respect-Validation-Validator 类(方法)源码代码实例,从而了解它的用法。

作者:rikniit    项目:legacy-php-boilerplat   
protected function setValidationRules($validator)
 {
     $required = new Validator();
     $required->notEmpty();
     $validator->attribute('name', $required);
     $validator->attribute('content', $required);
 }

作者:hamdre    项目:adventofcod   
/**
  * Returns the number of characters in memory after parsing given string.
  * @param string $string
  * @return int
  * @throws ParseException
  */
 public static function charsInMemory($string)
 {
     if (!Validator::stringType()->regex('/".*"/')->validate($string)) {
         throw new ParseException('String must be surrounded by double quotes (")');
     }
     return preg_match_all("/(\\\\\\\\|\\\\\"|\\\\x[[:xdigit:]]{2}|.)/", substr($string, 1, strlen($string) - 2));
 }

作者:easytaxib    项目:newreli   
public function __construct(Client $client, $key)
 {
     $this->client = $client;
     $this->key = $key;
     $baseUrl = $this->client->getConfig('base_uri');
     Validator::notEmpty()->url()->endsWith('/')->setName("URL for NewRelic's Insights API must be valid and have a trailing slash")->assert($baseUrl);
 }

作者:gurpreetatwa    项目:Skeleton-AP   
/**
  * Validator constructor.
  * @param array $rules Array where each key corresponds to one attribute of the model and the value is a list of
  *                     validation rules supported by Respect\Validation separated by the pipe ("|") character.
  */
 public function __construct(array $rules)
 {
     foreach ($rules as $field => $rule) {
         $this->addAttribute($field, $rule);
     }
     parent::__construct();
 }

作者:Tanklon    项目:openv   
protected function preprocessValue(&$uid)
 {
     if (!Validator::int($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $uid = (int) $uid;
 }

作者:HOF    项目:HOF   
public function validate($data)
 {
     $validator = V::key('name', V::string()->length(0, 100), true)->key('email', V::email()->length(0, 200), true)->key('password', V::string()->length(0, 100), true);
     try {
         $validator->assert($data);
         switch ($data['userable_type']) {
             case 'Designer':
                 $this->designerCreationValidator->validate($data);
                 $data['userable_type'] = DesignerModel::class;
                 break;
             case 'Administrator':
                 $this->adminCreationValidator->validate($data);
                 $data['userable_type'] = AdministratorModel::class;
                 break;
             case 'Buyer':
                 $this->buyerCreationValidator->validate($data);
                 $data['userable_type'] = BuyerModel::class;
                 break;
             default:
                 break;
         }
     } catch (AbstractNestedException $e) {
         $errors = $e->findMessages(['email', 'length', 'in']);
         throw new ValidationException('Could not create user.', $errors);
     }
     return true;
 }

作者:sunpaol    项目:slim3Dem   
public function index($params)
 {
     Validator::notEmpty()->setName('name')->check($params['name']);
     Validator::notEmpty()->setName('password')->check($params['password']);
     $levels = Config::loadData('level');
     $this->render('index.php', ['name' => $params['name']]);
 }

作者:Tanklon    项目:openv   
/**
  * @param string $category
  * @param string|null $subCategory
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function __construct($category, $subCategory = null)
 {
     if (!is_string($category)) {
         throw new InvalidArgumentException('category', 'type_invalid');
     }
     if (!mb_check_encoding($category, 'UTF-8')) {
         throw new InvalidArgumentException('category', 'encoding_invalid');
     }
     if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($category)) {
         throw new UserException('Problem.Tag.invalid_length');
     }
     $keyword = KeywordFilter::isContainGeneric($category);
     if ($keyword !== false) {
         throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
     }
     if (!is_string($subCategory)) {
         throw new InvalidArgumentException('subCategory', 'type_invalid');
     }
     if (!mb_check_encoding($subCategory, 'UTF-8')) {
         throw new InvalidArgumentException('subCategory', 'encoding_invalid');
     }
     if (!Validator::length(VJ::TAG_MIN, VJ::TAG_MAX)->validate($subCategory)) {
         throw new UserException('Problem.Tag.invalid_length');
     }
     $keyword = KeywordFilter::isContainGeneric($subCategory);
     if ($keyword !== false) {
         throw new UserException('Problem.Tag.name_forbid', ['keyword' => $keyword]);
     }
     $this->category = $category;
     $this->subCategory = $subCategory;
 }

作者:rindea    项目:allegro-clien   
public function __construct($webapiKey = null, $userLogin = null, $hashedPassword = null)
 {
     $this->properties['webapiKey'] = new Property(['validator' => function ($value) {
         try {
             Validator::string()->noWhitespace()->notEmpty()->length(4)->assert($value);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]);
     if (!is_null($webapiKey)) {
         $this->properties['webapiKey']->set($webapiKey)->lock();
     }
     // --------------------
     $this->properties['userLogin'] = new Property(['validator' => function ($value) {
         try {
             Validator::string()->noWhitespace()->notEmpty()->length(4)->assert($value);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]);
     if (!is_null($userLogin)) {
         $this->properties['userLogin']->set($userLogin)->lock();
     }
     // ----------------------
     $this->properties['hashedPassword'] = new Property(['validator' => function ($value) {
         try {
             Validator::string()->noWhitespace()->notEmpty()->regex('/^([A-Za-z0-9+\\/]{4})*([A-Za-z0-9+\\/]{4}|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{2}==)$/')->assert($value);
         } catch (NestedValidationExceptionInterface $e) {
             throw new ValidationException($e);
         }
     }]);
     if (!is_null($hashedPassword)) {
         $this->properties['hashedPassword']->set($hashedPassword)->lock();
     }
 }

作者:graz    项目:array-filte   
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']));
 }

作者:Tanklon    项目:openv   
/**
  * 创建并返回一个 token
  *
  * @param string $purpose
  * @param string|null $identifier 唯一标识,为空则不需要
  * @param int $expireAt
  * @param mixed $data
  * @param int $length
  * @return array
  * @throws InvalidArgumentException
  * @throws \Exception
  * @throws \MongoException
  */
 public function generate($purpose, $identifier, $expireAt, $data = null, $length = 30)
 {
     if (!is_string($purpose)) {
         throw new InvalidArgumentException('purpose', 'type_invalid');
     }
     if (!mb_check_encoding($purpose, 'UTF-8')) {
         throw new InvalidArgumentException('purpose', 'encoding_invalid');
     }
     if (!Validator::int()->validate($expireAt)) {
         throw new InvalidArgumentException('expireAt', 'type_invalid');
     }
     $token = Application::get('random')->generateString($length, VJ::RANDOM_CHARS);
     try {
         if ($identifier !== null) {
             if (!is_string($identifier)) {
                 throw new InvalidArgumentException('identifier', 'type_invalid');
             }
             if (!mb_check_encoding($identifier, 'UTF-8')) {
                 throw new InvalidArgumentException('identifier', 'encoding_invalid');
             }
             $result = Application::coll('Token')->update(['purpose' => $purpose, 'identifier' => $identifier], ['$set' => ['token' => $token, 'expireat' => new \MongoDate($expireAt), 'data' => $data]], ['upsert' => true]);
             return ['token' => $token, 'update' => $result['updatedExisting']];
         } else {
             $result = Application::coll('Token')->insert(['purpose' => $purpose, 'identifier' => null, 'token' => $token, 'expireat' => new \MongoDate($expireAt), 'data' => $data]);
             return ['token' => $token];
         }
     } catch (\MongoException $ex) {
         if ($ex->getCode() === 12) {
             throw new InvalidArgumentException('data', 'encoding_invalid');
         } else {
             throw $ex;
         }
     }
 }

作者:Tanklon    项目:openv   
/**
  * 加入域
  *
  * @param int $uid
  * @param \MongoId $domainId
  * @return bool
  * @throws InvalidArgumentException
  * @throws UserException
  */
 public function joinDomainById($uid, \MongoId $domainId)
 {
     if (!Validator::int()->validate($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $uid = (int) $uid;
     if (!DomainUtil::isGlobalDomainId($domainId)) {
         // 检查域是否存在
         $d = Application::coll('Domain')->findOne(['_id' => $domainId]);
         if (!DomainUtil::isDomainObjectValid($d)) {
             throw new UserException('DomainManager.joinDomain.invalid_domain');
         }
     }
     // 检查用户是否存在
     $user = UserUtil::getUserObjectByUid($uid);
     if (!UserUtil::isUserObjectValid($user)) {
         throw new UserException('DomainManager.joinDomain.invalid_user');
     }
     // 添加 MEMBER 角色
     Application::coll('UserRole')->update(['uid' => $uid], ['$addToSet' => ['d.' . (string) $domainId => 'DOMAIN_MEMBER']], ['upsert' => true]);
     // 创建空资料
     $document = ['pref' => new \stdClass(), 'rp' => 0.0, 'rp_s' => 0.0, 'rank' => -1, 'level' => 0];
     if (DomainUtil::isGlobalDomainId($domainId)) {
         $document += ['sig' => '', 'sigraw' => '', 'contacts' => []];
     }
     Application::coll('UserInfo')->update(['uid' => $uid, 'domain' => new \MongoId(VJ::DOMAIN_GLOBAL)], ['$setOnInsert' => $document], ['upsert' => true]);
     // 操作非全局域则插入操作记录
     if (!DomainUtil::isGlobalDomainId($domainId)) {
         $doc = ['uid' => $this->session->getCurrentToken(), 'at' => new \MongoDate(), 'type' => 'join', 'ua' => $this->request->getUserAgent(), 'ip' => $this->request->getClientIp(), 'target_uid' => $uid, 'target_domain' => $domainId];
         Application::coll('DomainLog')->insert($doc);
     }
     return true;
 }

作者:dindigita    项目:di   
public function validate($prop, $label)
 {
     $value = $this->getValue($prop);
     if (!v::string()->cnpj()->validate($value)) {
         $this->addException("O preenchimento do campo {$label} está inválido");
     }
 }

作者:vinyvicent    项目:credit-card-brand   
/**
  * @param $cardNumber
  * @return array
  * @throws NumberValidateException
  */
 public static function validate($cardNumber)
 {
     if (!v::numeric()->noWhitespace()->validate($cardNumber)) {
         throw new NumberValidateException();
     }
     return ['valid' => true, 'type' => 'visa'];
 }

作者:dindigita    项目:nfe-focu   
public function setAlternativeEmail($value)
 {
     if (!v::email()->validate($value)) {
         throw new FieldRequiredException("E-mail alternativo inválido");
     }
     $this->_email .= "," . $value;
 }

作者:pivnick    项目:acm   
public function isValid($validation_data)
 {
     $errors = [];
     foreach ($validation_data as $name => $value) {
         if (isset($_REQUEST[$name])) {
             $rules = explode("|", $value);
             foreach ($rules as $rule) {
                 $exploded = explode(":", $rule);
                 switch ($exploded[0]) {
                     case 'min':
                         $min = $exploded[1];
                         if (Valid::stringType()->length($min)->Validate($_REQUEST[$name]) == false) {
                             $errors[] = $name . " must be at least " . $min . " characters long";
                         }
                         break;
                     case 'email':
                         if (Valid::email()->Validate($_REQUEST[$name]) == false) {
                             $errors[] = $name . " must be a valid email ";
                         }
                         break;
                     case 'equalTo':
                         if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                             $errors[] = "Values do not match";
                         }
                         break;
                     default:
                         //do nothing
                 }
             }
         } else {
             $errors = "No value found";
         }
     }
     return $errors;
 }

作者:Aasi    项目:DISCOUNT--SRV-   
private function _validate($param, $type)
 {
     $libConfig = $GLOBALS['app']->getConfiguration()->getRawConfiguration('library');
     $minNameVal = $libConfig["product"]["minNameLength"];
     $maxNameVal = $libConfig["product"]["maxNameLength"];
     $minCodeVal = $libConfig["product"]["minCodeLength"];
     $maxCodeVal = $libConfig["product"]["maxCodeLength"];
     $validateName = v::alnum('-_')->length($minNameVal, $maxNameVal);
     $validateCode = v::alnum('-_')->noWhitespace()->length($minCodeVal, $maxCodeVal);
     $validateToken = v::alnum('-_');
     if (strcmp($type, "name") === 0) {
         $isValid = $validateName->validate($param);
         if (!$isValid) {
             throw new \InvalidArgumentException(\Akzo\Product\ErrorMessages::INVALID_PRODUCT_NAME, \Native5\Core\Http\StatusCodes::NOT_ACCEPTABLE);
         }
     } else {
         if (strcmp($type, "code") === 0) {
             $isValid = $validateCode->validate($param);
             if (!$isValid) {
                 throw new \InvalidArgumentException(\Akzo\Product\ErrorMessages::INVALID_PRODUCT_CODE, \Native5\Core\Http\StatusCodes::NOT_ACCEPTABLE);
             }
         } else {
             if (strcmp($type, "token") === 0) {
                 $isValid = $validateToken->validate($param);
                 if (!$isValid) {
                     throw new \InvalidArgumentException(\Akzo\Product\ErrorMessages::INVALID_TOKEN, \Native5\Core\Http\StatusCodes::NOT_ACCEPTABLE);
                 }
             } else {
                 throw new \InvalidArgumentException('Invalid Validation Type', \Native5\Core\Http\StatusCodes::NOT_ACCEPTABLE);
             }
         }
     }
 }

作者:10sun    项目:simple_for   
protected function validate()
 {
     $data = filter_input(INPUT_POST, $this->model);
     $error = false;
     foreach ($this->validation_rules as $field => $config) {
         $validator = new v();
         $validator->addRules($config['rules']);
         if ($config['optional']) {
             $this->validate[$field] = v::optional($validator);
         } else {
             $this->validate[$field] = $validator;
         }
         $error = $this->validate[$field]->validate($data[$field]);
     }
     return $error;
 }

作者:subtoni    项目:aouka_lunc   
/**
  * Execute la suite de tests.
  * 
  * @param mixed $void Ne sert à rien. Ne pas utiliser.
  * @return null|boolean Si vaut null, cela signifie que la valeur à tester n'existe pas.<br/>
  * Vaut TRUE ou FALSE selon la réussite de la suite des assertions.
  */
 public function validate($void = '')
 {
     if ($this->_bReturnNull) {
         return null;
     }
     return parent::validate($this->_mValueToTest);
 }

作者:jurajvu    项目:acm   
public function isValid($validation_data)
 {
     $errors = "";
     foreach ($validation_data as $name => $value) {
         $rules = explode("|", $value);
         foreach ($rules as $rule) {
             $exploded = explode(":", $rule);
             switch ($exploded[0]) {
                 case 'min':
                     $min = $exploded[1];
                     if (Valid::alpha()->length($min)->Validate($_POST[$name]) == false) {
                         $errors[] = $name . " must be at least " . $exploded[1] . " characters long!";
                     }
                     break;
                 case 'email':
                     if (Valid::email()->validate($_POST[$name]) == false) {
                         $errors[] = $name . " must be a valid email address!";
                     }
                     break;
                 case 'equalTo':
                     if (Valid::equals($_POST[$name])->validate($_POST[$exploded[1]]) == false) {
                         $errors[] = $name . "'s don't match!";
                     }
                     break;
                 default:
                     $errors[] = "No value found!";
                     break;
             }
         }
     }
     return $errors;
 }


问题


面经


文章

微信
公众号

扫码关注公众号