/** * 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]); }
/** * @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); } }
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()); } }
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()]; }
/** * 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 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()]; }
/** * 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 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); }
/** * 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 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; }
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 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; } }
/** * 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); }
/** * Validate the IodefElement's attributes and value. * @return boolval */ protected function validate() { // If attributes are set, validate them. if (!empty($this->attributes)) { // It's possible that there are no rules for the attributes available. // If so, skip attribute validation. if (sizeof($this->getAttributeRules()) > 0) { $validate_attributes = new Validator($this->attributes); $validate_attributes->rules($this->getAttributeRules()); // Validation failed to succeeed, show errors if (!$validate_attributes->validate()) { echo 'Some attributes failed to pass the validator:'; foreach ($validate_attributes->errors() as $failed_attr) { echo ' ' . $failed_attr[0]; } return false; } } } // If a value is set, validate it. if (array_key_exists('value', $this)) { // It's possible that there is no value rule set. // If so, skip value validation. if (sizeof($this->getValueRule()) > 0) { $validate_value = new Validator(['value' => $this->value]); $validate_value->rules($this->getValueRule()); // Validation failed to succeeed, show errors if (!$validate_value->validate()) { echo 'The value failed to pass the validator:'; foreach ($validate_value->errors() as $message) { echo ' ' . $message; } return false; } } } return true; }
/** * @param $rule * @param $value * @return bool */ private function applyValidationRules($rule, $value, $fields = array()) { /** * @TODO all validation script should be written here. */ if ($rule == 'notEmpty') { $v = new Validator(array('name' => $value)); $v->rule('required', 'name'); if ($v->validate()) { return true; } return false; } elseif ($rule == 'email') { $v = new Validator(array('email' => $value)); $v->rule('email', 'email'); if ($v->validate()) { return true; } return false; } elseif ($rule == 'matchPassword') { if (isset($fields->password) && $value == $fields->password) { return true; } return false; } else { return false; } }
/** * Run validation against $this->rules * * @param array $data * @return Message|bool */ public static function validate(array $data) { $validator = new Validator($data); $validator->rules(static::$rules); if ($validator->validate()) { return true; } else { return new Message($validator->errors()); } }
/** * Validate an object using the data and rules passed in * * Will update the last result with validation errors * * @param array $aData The data to validate * @param array $aRules The results to apply * * @return boolean true if valid false otherwise */ public function validate($aData, $aRules) { $oValidator = new Validator($aData); $oValidator->rules($aRules); $bValid = $oValidator->validate(); if (false === $bValid) { $this->aLastResult['result'] = false; $this->aLastResult['msg'] = $oValidator->errors(); } return $bValid; }
$array[$key] = []; } return $array[$key]; } $logger = Logger::getLogger('services/saveProfile'); $numeroMembre = LemonLdap::getCurrentUserId(); $logger->debug("Found current user id: {$numeroMembre}"); //$logger->debug("Reveived form data: ".print_r($_POST,true)); $v = new Validator($_POST); $v->rule('required', ['adresse1', 'codePostal', 'ville', 'pays'])->message('{field} doit être renseigné.'); $v->rule('email', 'email')->message('{field} n\'est pas une adresse email valide.'); $v->rule('in', 'statut', [null, '', 'single', 'couple', 'deceased'])->message('{field} n\'est pas valide.'); $v->rule('integer', 'enfants')->message('{field} n\'est pas un nombre entier.'); $MAX_LENGTHS = ['adresse1' => 35, 'adresse2' => 35, 'adresse3' => 35, 'codePostal' => 20, 'ville' => 50, 'pays' => 50, 'telephone' => 20, 'email' => 127]; header("Content-type: application/json; charset=utf-8'"); if ($v->validate()) { $formValues = $_POST; foreach ($MAX_LENGTHS as $key => $value) { $formValues[$key] = Format::limitLength($formValues[$key], $MAX_LENGTHS[$key]); } $foundProfile = Doctrine::findMembre($numeroMembre); // Don't generate method calls to avoid potential security hole. $foundProfile->setStatut($formValues['statut']); $foundProfile->setEnfants($formValues['enfants']); $foundProfile->setDevise($formValues['devise']); $foundProfile->setCoordonnee('email', $formValues['email'], $formValues['emailPrive']); $foundProfile->setCoordonnee('phone', $formValues['telephone'], $formValues['telephonePrive']); $adresseValue = ['address' => trim("{$formValues['adresse1']}\n{$formValues['adresse2']}\n{$formValues['adresse3']}"), 'code' => $formValues['codePostal'], 'city' => $formValues['ville'], 'country' => $formValues['pays']]; $foundProfile->setCoordonnee('address', json_encode($adresseValue), $formValues['adressePrivee']); $foundProfile->setLangues(getArrayValue($formValues, 'langues')); $foundProfile->setCompetences(getArrayValue($formValues, 'competences'));
/** * Processes the validation group * @param array $data * @return \Valitron\boolean */ public function val(array $data) { $this->_fields = $data; $labels = array(); foreach ($data as $key => $value) { $labels[$key] = ucwords(str_replace('_', ' ', $key)); } $this->labels($labels); return parent::validate(); }
public function testInstanceOfWithAlternativeSyntaxInvalid() { $v = new Validator(array('attributeName' => new stdClass())); $v->rules(array('instanceOf' => array(array('attributeName', 'SomeOtherClassInAlternativeSyntaxInvalid')))); $v->validate(); $this->assertFalse($v->validate()); }
public function validate($data) { $v = new Validator($data); $v->rules($this->rules); return $v->validate(); }
public function testCustomLabelArrayWithoutMessage() { $v = new Valitron\Validator(array('password' => 'foo', 'passwordConfirm' => 'bar')); $v->rule('equals', 'password', 'passwordConfirm'); $v->labels(array('password' => 'Password', 'passwordConfirm' => 'Password Confirm')); $v->validate(); $this->assertEquals(array('password' => array("Password must be the same as 'Password Confirm'")), $v->errors()); }
/** * Validates if the assign properties are valid for a * database insert * * @return boolean true if */ public function validate() { $aFields = array('voucherGenRuleID' => $this->getVoucherGenRuleId(), 'slugName' => $this->getSlugRuleName(), 'voucherRuleName' => $this->getVoucherRuleName(), 'voucherPaddingChar' => $this->getVoucherPaddingCharacter(), 'voucherSuffix' => $this->getVoucherSuffix(), 'voucherPrefix' => $this->getVoucherPrefix(), 'voucherLength' => $this->getVoucherLength(), 'sequenceStrategy' => $this->getSequenceStrategyName()); // ensure total length < 255 column size for the voucher code // generated with the current db schema and size of padding,suffix $iTotalLength = (int) $this->getVoucherLength(); $iTotalLength += mb_strlen((string) $this->getVoucherSuffix()); $iTotalLength += mb_strlen((string) $this->getVoucherPrefix()); $aFields['totalLength'] = $iTotalLength; $v = new Validator($aFields); $v->rule('slug', 'slugName'); $v->rule('length', array('voucherPaddingChar'), 1); $v->rule('lengthBetween', array('slugName', 'name'), 1, 25); $v->rule('lengthBetween', array('voucherSuffix', 'voucherPrefix'), 0, 50); $v->rule('lengthBetween', array('totalLength'), 1, 255); $v->rule('required', array('slugName', 'voucherRuleName', 'voucherLength')); $v->rule('min', array('voucherGenRuleID', 'voucherLength'), 1); $v->rule('max', array('voucherLength'), 100); // this number of characters in unique number not max possible number $v->rule('in', array('sequenceStrategy'), array('UUID', 'SEQUENCE')); if ($v->validate()) { return true; } else { return $v->errors(); } }
/** * Validates if the assign properties are valid for a database insert * * @return boolean true if */ public function validate() { $aFields = array('voucherCode' => $this->getVoucherCode(), 'voucherTypeId' => $this->getVoucherTypeId(), 'voucherInstanceId' => $this->getVoucherInstanceId()); $v = new Validator($aFields); $v->rule('lengthBetween', array('voucherCode'), 1, 255); $v->rule('required', array('voucherCode', 'voucherTypeId')); $v->rule('min', array('voucherInstanceId'), 1); if ($v->validate()) { return true; } else { return $v->errors(); } }
public function testIfNotSetIsNotSetNotProvided() { $v = new Validator(array('firstname' => 'Daniel')); $v->rule('ifNotSet', 'name', array('rule' => 'required', 'field' => 'lastname')); $this->assertFalse($v->validate()); }
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); }
static function callValitron($arr, $rules, $throw = TRUE) { $v = new Validator($arr); $v->rules($rules); if (!$v->validate()) { if ($throw) { throw (new \RoyalMail\Exception\RequestException())->withErrors($v->errors()); } return $v->errors(); } else { return TRUE; } }
public function testWithData() { $v = new Validator(array()); $v->rule('required', 'name'); //validation failed, so must have errors $this->assertFalse($v->validate()); $this->assertNotEmpty($v->errors()); //create copy with different data $v2 = $v->withData(array('name' => 'Chester Tester')); $this->assertTrue($v2->validate()); $this->assertEmpty($v2->errors()); }