Наследование: extends Respect\Validation\Rules\AllOf
Пример #1
0
 protected function setValidationRules($validator)
 {
     $required = new Validator();
     $required->notEmpty();
     $validator->attribute('name', $required);
     $validator->attribute('content', $required);
 }
Пример #2
0
 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");
     }
 }
 /**
  * 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));
 }
Пример #4
0
 /**
  * @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'];
 }
Пример #5
0
 public function setAlternativeEmail($value)
 {
     if (!v::email()->validate($value)) {
         throw new FieldRequiredException("E-mail alternativo inválido");
     }
     $this->_email .= "," . $value;
 }
Пример #6
0
 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);
 }
Пример #7
0
 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;
 }
Пример #8
0
 /**
  * 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();
 }
Пример #9
0
 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);
             }
         }
     }
 }
Пример #10
0
 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;
 }
Пример #11
0
 /**
  * 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);
 }
Пример #12
0
 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;
 }
Пример #13
0
 /**
  *  init valid rule
  */
 protected function initRule()
 {
     $this->validRule['id'] = v::numeric();
     $this->validRule['name'] = v::stringType()->length(1, 10);
     $this->validRule['email'] = v::email();
     $this->validRule['sex'] = v::intVal()->between(0, 1);
 }
Пример #14
0
 protected function preprocessValue(&$uid)
 {
     if (!Validator::int($uid)) {
         throw new InvalidArgumentException('uid', 'type_invalid');
     }
     $uid = (int) $uid;
 }
Пример #15
0
 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;
 }
Пример #16
0
 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']]);
 }
Пример #17
0
 public function validate($prop, $label)
 {
     $value = $this->getValue($prop);
     if (!v::string()->notEmpty()->validate($value)) {
         $this->addException("O campo {$label} é de preenchimento obrigatório");
     }
 }
Пример #18
0
 /**
  * Saves a setting as a key/value pair
  *
  * Settings specific to fast-forward start with a `ff.` prefix.
  *
  * You can use the constants of this class to avoid looking up the key names.
  *
  * @param string $key   Unique key name.<br>
  *                      Must contain only letters (a-z, A-Z), digits (0-9) and "."
  * @param string $value
  *
  * @throws \Exception
  */
 public function set($key, $value)
 {
     $out = $this->client->getOutput();
     try {
         v::string()->alnum('.')->noWhitespace()->notEmpty()->assert($key);
     } catch (NestedValidationExceptionInterface $e) {
         $out->error($e->getFullMessage());
         return;
     }
     $setting = $this->get($key, true);
     if ($setting === null) {
         $setting = new Setting();
         $setting->key = $key;
     }
     $oldValue = $setting->value;
     $setting->value = $value;
     if (!$this->validate($setting)) {
         return;
     }
     if ($oldValue === null) {
         $out->writeln("Inserting new setting:\n{$key} = <options=bold>{$value}</>");
     } elseif ($oldValue !== $value) {
         $out->writeln("Changing setting:\n{$key} = {$oldValue} --> <options=bold>{$value}</>");
     } else {
         $out->writeln("Setting already up-to-date:\n{$key} = {$value}");
     }
     $setting->save();
 }
Пример #19
0
 /**
  * @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;
 }
Пример #20
0
 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();
     }
 }
 /**
  * @param   $param
  * @return  string
  * @throws  EntityValidationException
  */
 public function password($param)
 {
     if (!v::notEmpty()->length(2, 100)->validate($param)) {
         throw new EntityValidationException('User', 'password', $param, 'length must be between 2 and 100');
     }
     return $param;
 }
Пример #22
0
 public function post()
 {
     try {
         $newManufacturer = (object) (['id' => null] + $_POST);
         v::arr()->key('name', v::string()->notEmpty()->length(1, 300))->assert($_POST);
         if ($_FILES['files']['error'] == 4) {
             throw new Exception('O campo imagem é obrigatório');
         }
         if (empty($newManufacturer->manufacturer_featured)) {
             $newManufacturer->manufacturer_featured = null;
         }
         $this->collection->persist($newManufacturer);
         $this->collection->flush();
         foreach ($_FILES as $file) {
             $this->uploaderService->setFile($_POST['name'], 'files');
             $image = (object) ['name' => $this->uploaderService->getFile()->getNameWithExtension(), 'title' => $_POST['name'], 'type' => $this->uploaderService->getFile()->getMimetype(), 'manufacturer_id' => $newManufacturer->id];
             $this->imageCollection->persist($image);
             $this->imageCollection->flush();
             $this->uploaderService->upload();
         }
         header('HTTP/1.1 303 See Other');
         header('Location: /catalog/manufacturers');
     } catch (NestedValidationExceptionInterface $e) {
         return $this->get() + ['manufacturer/addManufacturer' => $newManufacturer, 'messages' => $e->findMessages(['name' => 'O nome deve ser entre 1 e 300 caracteres'])];
     }
 }
Пример #23
0
 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']));
 }
Пример #24
0
 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::stringType()->length($min, null)->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 address!";
                     }
                     break;
                 case 'equalTo':
                     if (Valid::equals($_REQUEST[$name])->Validate($_REQUEST[$exploded[1]]) == false) {
                         $errors[] = "Value does not match verification value!";
                     }
                     break;
                 default:
                     $errors[] = "No value found!";
             }
         }
     }
     return $errors;
 }
Пример #25
0
 public function post($manufacturerId)
 {
     $editManufacturer = $this->collection[$manufacturerId]->fetch() ?: new stdClass();
     foreach ($_POST as $k => $v) {
         $editManufacturer->{$k} = $v;
     }
     try {
         v::object()->attribute('name', v::string()->notEmpty()->length(1, 300))->assert($editManufacturer);
         $this->collection->persist($editManufacturer);
         $this->collection->flush();
         if (empty($newManufacturer->manufacturer_featured)) {
             $newManufacturer->manufacturer_featured = null;
         }
         if ($_FILES['files']['error'] != 4) {
             foreach ($_FILES as $file) {
                 $this->uploaderService->setFile($editManufacturer->name, 'files');
                 $image = (object) ['name' => $this->uploaderService->getFile()->getNameWithExtension(), 'title' => $editManufacturer->name, 'type' => $this->uploaderService->getFile()->getMimetype(), 'manufacturer_id' => $editManufacturer->id];
                 $this->imageCollection->persist($image);
                 $this->imageCollection->flush();
                 $this->uploaderService->upload();
             }
         }
         header('HTTP/1.1 303 See Other');
         header('Location: ' . $_SERVER['REQUEST_URI']);
     } catch (NestedValidationExceptionInterface $e) {
         return ['editManufacturer' => $editManufacturer, 'messages' => $e->findMessages(['name' => 'Name must have between 1 and 300 chars', 'enabled' => 'Could not enable manufacturer'])];
     }
 }
Пример #26
0
 public function setJustification($justification)
 {
     if (!v::string()->length(15, 1000)->validate($justification)) {
         throw new FieldRequiredException("A justicativa deve ter entre 15 e 100 caracteres");
     }
     $this->_justification = $justification;
 }
Пример #27
0
 /**
  * 创建并返回一个 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;
         }
     }
 }
Пример #28
0
function OrderTable($ordersProducts, $connection)
{
    foreach ($ordersProducts as $arrayNumber => $orders_data) {
        echo "<tr class='product'>";
        foreach ($orders_data as $data_key => $data_value) {
            //echo "data-key: ".$data_key." data-value: ".$data_value."<br>";
            switch ($data_key) {
                case "product_id":
                    $product = \App\DB\Products::get($data_value, $connection);
                    $flag = v::arr()->notEmpty()->validate($product);
                    if ($flag) {
                        printProduct($product);
                    } else {
                        echo "<td class='deleted-product' colspan='2'>Товар удален из базы данных</td>";
                    }
                    break;
                case "amount":
                    echo "<td data-amount='{$data_value}'>" . $data_value . "</td></tr>";
                    break;
                default:
                    break;
            }
        }
    }
}
Пример #29
0
 /**
  * 加入域
  *
  * @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;
 }
Пример #30
0
 public function validate($prop, $label)
 {
     $v = $this->getValue($prop);
     if (!v::min($this->_min, true)->max($this->_max, true)->validate($v)) {
         $this->addException("O campo {$label} deve conter um número entre {$this->_min} e {$this->_max}");
     }
 }