/** * Fix bug where rules messages added with Validator::addRule were replaced after creating validator instance */ public function testRuleMessagesReplacedAfterConstructor() { $customMessage = 'custom message'; $ruleName = 'customRule'; $fieldName = 'fieldName'; Validator::addRule($ruleName, function () { }, $customMessage); $v = new Validator(array($fieldName => $fieldName)); $v->rule($ruleName, $fieldName); $v->validate(); $messages = $v->errors(); $this->assertArrayHasKey($fieldName, $messages); $this->assertEquals(ucfirst("{$fieldName} {$customMessage}"), $messages[$fieldName][0]); }
/** * Registers a user with the details within the HTTP Request object if no user currently exists * with a matching username or email address. * * @param Request $request The HTTP Request object. * @param Response $response The HTTP Response object. * @param array $args The array containing arguments provided. * * @return string The message from the registration process. */ public function register(Request $request, Response $response, array $args) { //get post variables from request body $post = $request->getParams(); //validate post variables (exist, and as expected) /** @var Validator $v */ $v = new Validator($post); $v->rule('required', ['username', 'password', 'email', 'first_name', 'last_name', 'date_of_birth']); $v->rule('email', 'email'); $ret = array(); if ($v->validate()) { if ($this->dbService->userExists($post['username'], $post['email'])) { $ret['message'] = "User already exists."; $ret['success'] = false; } else { if ($key = $this->dbService->addNewUser($post) ?: false) { $this->emailService->sendVerificationEmail($post['email'], $post['first_name'], $post['last_name'], $key); $ret['message'] = "You are now registered! A confirmation email has been sent to you. Please open it and follow\r\n the instructions provided."; $ret['success'] = true; } else { $ret['message'] = "Something went wrong. Please try again later."; $ret['success'] = false; } } } else { $ret['message'] = "Please complete all fields."; $ret['success'] = false; } return json_encode($ret); }
function validateAddPlaceForm($place) { $v = new Validator($place); $v->rule('required', ['name', 'address', 'tag_id']); $v->rule('lengthMin', ['name'], 3); return ['is_valid' => $v->validate(), 'has_errors' => $v->errors()]; }
public function prosesAdd() { if ($this->petugas == null) { header("Location: " . base . "/Auth"); exit; } $valid = new Validator($_POST); $valid->rule('required', ['title', 'author', 'publisher', 'category']); if ($valid->validate()) { $book = new Book(); $book->BookTitle = $_POST['title']; $book->BookAuthor = $_POST['author']; $book->PublisherID = $_POST['publisher']; $book->CategoryID = $_POST['category']; $book->BookPageCount = $_POST['pageCount']; $book->BookPublished = $_POST['year']; $book->BookDescription = $_POST['des']; $book->BookPhoto = "acas"; $book->BookDateAdd = Carbon::now(); $book->BookPrice = $_POST['price']; if ($book->save()) { if ($_FILES['photo']['name'] != "") { $uploaddir = '/var/www/limsmvc/img/'; $uploadfile = $uploaddir . $book->BookID; move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile); } } header("Location: " . base . "/Book"); } else { // Errors print_r($valid->errors()); } }
public static function validatorHook(Validator $v) { $v->addRule('testHook', function ($field, $value, array $params) { return false; }); return $v; }
/** * @param Request $request * @param Response $response * @param $next * @return Response */ public function __invoke(Request $request, Response $response, $next) { if ($this->validator->validate()) { return $next($request, $response); } else { return $response->withJson($this->validator->errors(), 400); } }
/** * Retrieve validator for this entity * * @param Array $data Data to be validated * @return Validator */ public function getValidator($data) { $validator = new Validator($data); $validator->rule('required', 'name'); $validator->rule('lengthBetween', 'name', 1, 100); $validator->labels(['name' => 'Name']); return $validator; }
/** * Validate required parameters for URL Generation. * * @param array $params * @throws ValidationException */ protected function validate(array $params) { $validator = new Validator($params); $validator->rule('required', $this->rules); if (!$validator->validate()) { $errors = ''; foreach ($validator->errors() as $key => $value) { $errors .= $key . ' is required. '; } throw new ValidationException($errors); } }
/** * Method that validates fields of the entity based on its restrictions */ protected function validateFields() { $validator = new Validator($this->data, [], 'en'); //@todo: if use external i18n library? if ($this->action == 'new') { $validator->rules(array_merge($this->rulesNew, $this->rulesGlobal)); } else { $validator->rules(array_merge($this->rulesModify, $this->rulesGlobal)); } if (!$validator->validate()) { $this->errors = array_merge($this->errors, $validator->errors()); } }
/** * validasi * @param array $data POST data * @return boolean */ public function validate($data) { $v = new Validator($data, [], 'id'); foreach ($this->rules as $rule => $columns) { $v->rule($rule, $columns); } $v->labels($this->labels); if ($v->validate()) { return true; } else { $this->errors = $v->errors(); return false; } }
private function validate($data) { $v = new Validator($data); $v->rule('required', ['gender', 'age', 'height', 'weight']); $v->rule('numeric', ['age', 'height', 'weight']); $v->rule('in', 'gender', [self::MALE, self::FEMALE])->message('Gender must be specified'); $v->rule('max', 'height', 2.5); $v->rule('notIn', 'height', [0])->message('{field} - zero is not allowed here'); $v->rule('min', 'weight', 30); $v->rule('min', 'age', 21)->message('This formula applies only to adults (more than 21 years old )'); $this->valid = $v->validate(); $this->errors = $v->errors(); d($this->errors); }
private function validateConfig($config) { if (!is_array($config)) { // Throw exception throw new InvalidDataTypeFoundException("Expected array but found " . gettype($config) . " instead", 1004); } $validator = new Valitron($config); $validator->rule('required', ['AKAMAI_KEY', 'AKAMAI_KEYNAME', 'AKAMAI_HOST']); $validator->rule('length', 'AKAMAI_KEY', 50); if (!$validator->validate()) { // Concatinate all message and Throw exception $message = implode(', ', ArrayHelper::flatten($validator->errors())); throw new ValidationException($message, 1007); } return $config; }
function loadCustomRules() { parent::loadCustomRules(); $this->didCustomRules = true; \Valitron\Validator::addRule('customRule', function ($field, $value, $params) { return $value === 'foo'; }, 'values must be foo'); }
static function loadStaticRules() { if (self::$staticRulesLoaded) { return; } \Valitron\Validator::addRule('safeText', array('Arrow\\Options\\Validator', 'isSafeText')); self::$staticRulesLoaded = true; }
/** * Validate the specified data against the schema rules. * * @param array $data An array of data, mapping field names to field values. * @return boolean True if the data was successfully validated, false otherwise. */ public function validate($data = []) { $this->_fields = $data; // Setting the parent class Validator's field data. $this->generateSchemaRules(); // Build Validator rules from the schema. return parent::validate(); // Validate! }
public function __construct($params) { date_default_timezone_set('UTC'); ValitronValidator::lang('ru'); ValitronValidator::addRule('stringWords', function ($field, $value, array $params) { return count(explode(' ', $value)) <= $params[0]; }, 'должно содержать не более слов: %s'); self::$validator = new ValitronValidator($params); }
public function __construct($data, $lang = 'ja') { V::addRule('katakana', function ($field, $value, array $params) { if (preg_match('/^[ァ-ヶー]+$/u', $value)) { return true; } return false; }, 'はカタカナで入力してください'); parent::__construct($data, $lang); }
/** * Form constructor. * @param string $formId Form identificator * @param array $post $_POST data array * @param \DigitalHammer\LpForms\Mailer $mailer Mailer instance * @param string $lang language for validator */ public function __construct($formId, array $post, $mailer, $lang = 'ru') { $this->formId = $formId; $this->post = $post; $this->mailer = $mailer; Validator::lang($lang); $this->validator = new Validator($this->post); $this->response = new ResponseJson(); $this->setMessageBodyTemplate($formId); }
public function __construct($app, $em) { /* @var $app Slim */ Validator::addRule('unique_storename', function ($field, $value, array $params) use($em, $app) { $storename = $app->request->post('winkelnaam'); $repo = $em->getRepository('digi\\eslTools\\Entities\\Store'); $result = $repo->findBy(array('storename' => $storename)); return count($result) < 1; }, 'bestaat al'); parent::__construct($app, $em); }
public function testUniqueRuleName() { $v = new Validator(array()); $args = array("foo", "bar"); $this->assertEquals("foo_bar_rule", $v->getUniqueRuleName($args)); $this->assertEquals("foo_rule", $v->getUniqueRuleName("foo")); $v->addInstanceRule("foo_rule", function () { }); $u = $v->getUniqueRuleName("foo"); $this->assertRegExp("/^foo_rule_[0-9]{1,5}\$/", $u); }
public function validate($datas = []) { foreach (get_class_methods($this) as $funcRule) { if (stripos($funcRule, 'rule') === 0 && $funcRule != 'rules') { $args = $this->{$funcRule}(); array_unshift($args, lcfirst(str_replace('rule', '', $funcRule))); call_user_func_array('\\Valitron\\Validator::addRule', $args); } } if ($datas == null) { $datas = get_object_vars($this); } $validator = new Validator($datas); foreach ($this->rules() as $args) { call_user_func_array([$validator, 'rule'], $args); } if ($validator->validate()) { return null; } return $validator->errors(); }
public function __construct($data, $lang = 'ja') { V::lang($lang); if ($data instanceof Params) { $data = $data->toArray(); } elseif (!is_array($data)) { throw new \RuntimeException('$data should be array or Params'); } $this->v = new V($data); $this->labels(); $this->rules(); }
/** * Creates the validator. * * @return \Valitron\Validator */ protected function createValidator() { $validator = new ValitronValidator($this->data); array_walk($this->rules, function ($rules, $field) use(&$validator) { foreach ($rules as $rule => $option) { if (is_numeric($rule)) { list($rule, $option) = [$option, null]; } $validator->rule($rule, [$field], $option); } }); return $validator; }
function validateUserEditForm($user) { $v = new Validator($user); $v->rule('required', ['full_name', 'email']); $v->rule('lengthMin', ['full_name'], 3); $v->rule('email', 'email'); return ['is_valid' => $v->validate(), 'has_errors' => $v->errors()]; }
/** * Authenticates a user if given the correct username and password. * * @param Request $request The HTTP Request object. * @param Response $response The HTTP Response object. * @param array $args The array containing arguments provided. * * @return string The message from the authentication process. */ public function authenticate(Request $request, Response $response, array $args) { //get post variables from request body $post = $request->getParams(); //validate post variables (exist, and as expected) /** @var Validator $v */ $v = new Validator($post); $v->rule('required', ['username', 'password']); $ret = array(); //if validation fails, exit, else authenticate if ($v->validate()) { if (password_verify($post['password'], $this->dbService->getPassword($post['username']))) { $user = $this->dbService->getUser($post['username']); if ($user) { if ($this->dbService->hasVerified($post['username'])) { $remember = $post['remember']; $this->startSession($user, $remember); $ret['success'] = true; $ret['message'] = "authenticated"; } else { $ret['success'] = false; $ret['message'] = "This account has not yet been verified."; } } else { $ret['success'] = false; $ret['message'] = "Incorrect username and/or password"; } } else { $ret['success'] = false; $ret['message'] = "Incorrect username and/or password"; } } else { $ret['success'] = true; $ret['message'] = "Please enter your username and password."; } return json_encode($ret); }
public function register() { $di = $this->getContainer(); $config = $this->getConfig(); if (!is_null($config['locales_dir'])) { Validator::langDir($config['locales_dir']); } Validator::lang($config['locale']); foreach ($config['rules'] as $rule) { call_user_func_array('Valitron\\Validator::addRule', $rule); } $di->add('Valitron\\Validator', function ($data, $fields = [], $lang = null, $langDir = null) { return new Validator($data, $fields, $lang, $langDir); }); }
public function testCustomLabels() { $messages = array('name' => array('Name is required'), 'email' => array('Email should be a valid email address')); $v = new Validator(array('name' => '', 'email' => '$')); $v->rule('required', 'name')->message('{field} is required'); $v->rule('email', 'email')->message('{field} should be a valid email address'); $v->labels(array('name' => 'Name', 'email' => 'Email')); $v->validate(); $errors = $v->errors(); $this->assertEquals($messages, $errors); }
public function __construct($app, $em) { // custom rule unique email Validator::addRule('unique_email', function ($field, $value, array $params) use($em, $app) { $email = $app->request->post('e-mail'); $repo = $em->getRepository('digi\\eslTools\\Entities\\User'); $result = $repo->findBy(array('email' => $email)); return count($result) < 1; }, 'bestaat al'); // custom rule unique username Validator::addRule('unique_username', function ($field, $value, array $params) use($em, $app) { $username = $app->request->post('gebruikersnaam'); $repo = $em->getRepository('digi\\eslTools\\Entities\\User'); $result = $repo->findBy(array('username' => $username)); return count($result) < 1; }, 'bestaat al'); parent::__construct($app, $em); // custom rule }
public static function attempt(array $credentials, $remember_me = false) { $input_email = filter_var($credentials['email'], FILTER_SANITIZE_STRING); $input_password = filter_var($credentials['pass'], FILTER_SANITIZE_STRING); //run validation $v = new Validator($credentials); $v->rule('email', 'email')->message('Please provide an valid Email address'); $v->rule('required', 'email')->message('Email is required'); $v->rule('required', 'pass')->message('Please provide an password'); if (!$v->validate()) { return array('errors' => $v->errors()); } //data valid so proceed to next try { $m = new \QueryBuilder(); $user = $m->select('users', array('email = :email', array('email' => array($input_email, \PDO::PARAM_STR)))); if (!$user) { throw new \Exception('No user found with this credential', 5002); } $stored_password_hash = $user['password']; if (password_verify($input_password, $stored_password_hash)) { $_SESSION['auth.user.logged_in'] = true; $_SESSION['auth.user.id'] = $user['id']; if ($remember_me === true) { $auth_config = load_config('auth'); //set token and it's validity period $remember_token = uniqid('rem_'); $remember_validity = time() + $auth_config['login_cookie_expire']; $m->update('users', array('remember_token' => array($remember_token, \PDO::PARAM_STR), 'token_validity' => array(date('Y-m-d H:i:s', $remember_validity), \PDO::PARAM_STR)), array('id = :id', array('id' => array(intval($user['id']), \PDO::PARAM_INT)))); setcookie($auth_config['login_cookie_name'], $remember_token, $remember_validity); } return true; } else { throw new \Exception('Invalid credential. Please provide valid username and password.', 5003); } } catch (\Exception $ex) { throw $ex; } }
$model = new ReflectionClass($class); if (!$model->isSubclassOf(Models::class)) { throw new InvalidArgumentException(sprintf('Data model must be instance of %s, %s given', Models::class, $model->getName())); } return $model->newInstance($db, $session); }; }; /** * Setup validator container * * @return \Valitron\Validator */ $container['validator'] = function ($container) { $request = $container->get('request'); $viewData = $container->get('view')->getPlates()->getData('sections::captcha'); $validator = new Validator($request->getParams(), [], 'id'); if ($viewData['gcaptchaEnable'] == true) { $remoteAddr = $container->get('environment')->get('REMOTE_ADDR'); $validator->addRule('verifyCaptcha', function ($field, $value, array $params) use($viewData, $remoteAddr) { if (isset($field['g-recaptcha-response'])) { $recaptcha = new ReCaptcha\ReCaptcha($viewData['gcaptchaSecret']); return $recaptcha->verify($field['g-recaptcha-response'], $remoteAddr)->isSuccess(); } return false; }, 'Verifikasi captcha salah!'); $validator->rule('verifyCaptcha', 'captcha'); } return $validator; }; /** * Setup flash message container