errors() public méthode

Get array of error messages
public errors ( null | string $field = null ) : array | boolean
$field null | string
Résultat array | boolean
 /**
  * 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);
     }
 }
Exemple #3
0
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()];
}
Exemple #4
0
 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 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()];
}
 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 testAddAddRuleWithCallbackFailMessage()
 {
     $v = new Validator(array("foo" => "baz"));
     $v->rule(function ($field, $value) {
         return $field === "foo" && $value === "bar";
     }, "foo", "test error message");
     $this->assertFalse($v->validate());
     $errors = $v->errors();
     $this->assertArrayHasKey("foo", $errors);
     $this->assertCount(1, $errors["foo"]);
     $this->assertEquals("Foo test error message", $errors["foo"][0]);
 }
 /**
  * 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());
     }
 }
Exemple #10
0
 /**
  * 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;
     }
 }
Exemple #11
0
 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;
 }
Exemple #12
0
 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();
 }
Exemple #13
0
 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;
     }
 }
Exemple #14
0
 /**
  * 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;
 }
 /**
  * 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;
 }
Exemple #16
0
 /**
  * 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());
     }
 }
    $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'));
    $foundProfile->setPassions(getArrayValue($formValues, 'passions'));
    Doctrine::persist($foundProfile);
    Doctrine::flush();
    $ldapResult = LdapSync::updateProfile($numeroMembre, $foundProfile->jsonSerialize());
    if ($ldapResult) {
        // Then it's an error.
        $logger->error("Ldap error updating status for #{$numeroMembre}: {$ldapResult}");
    }
    echo json_encode($foundProfile);
} else {
    $logger->info('Found validation errors: ' . print_r($v->errors(), true));
    $errors = [];
    foreach ($v->errors() as $fieldName => $fieldErrors) {
        foreach ($fieldErrors as $message) {
            $errors[] = $message;
        }
    }
    $logger->info('Found validation errors: ' . print_r($errors, true));
    echo json_encode(['errors' => $errors]);
}
Exemple #18
0
 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());
 }
Exemple #19
0
 public function testInstanceOfErrorMessageShowsInstanceName()
 {
     $v = new Validator(array('attributeName' => new Validator(array())));
     $v->rule('instanceOf', 'attributeName', new stdClass());
     $v->validate();
     $expected_error = array("attributeName" => array("AttributeName must be an instance of 'stdClass'"));
     $this->assertEquals($expected_error, $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();
     }
 }
 /**
  * Validates if the assign properties are valid for a
  * database insert
  * 
  * @return boolean true if 
  */
 public function validate()
 {
     $aFields = array('voucherID' => $this->getVoucherGroupId(), 'name' => $this->getVoucherGroupName(), 'sortOrder' => $this->getSortOrder(), 'isDisabled' => $this->getDisabledStatus(), 'slugName' => $this->getSlugName());
     $v = new Validator($aFields);
     $v->rule('slug', 'slugName');
     $v->rule('lengthBetween', array('slugName', 'name'), 1, 100);
     $v->rule('required', array('slugName', 'name', 'isDisabled'));
     $v->rule('min', array('voucherID'), 1);
     if ($v->validate()) {
         return true;
     } else {
         return $v->errors();
     }
 }
 private function validateBillingParams($params)
 {
     $validator = new Validator($params);
     $validator->rule('required', ['transactionId', 'firstName', 'lastName', 'address1', 'address2', 'city', 'state', 'country', 'telNo', 'email']);
     if (!$validator->validate()) {
         $errors = '';
         foreach ($validator->errors() as $key => $value) {
             $errors .= $key . ' is required. ';
         }
         throw new ValidationException($errors);
     }
 }
Exemple #23
0
 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());
 }
Exemple #24
0
 /**
  * @dataProvider dataProviderFor_testError
  */
 public function testError($expected, $input, $test, $message)
 {
     $v = new Validator(array('test' => $input));
     $v->error('test', $message, $test);
     $this->assertEquals(array('test' => array($expected)), $v->errors());
 }
 /**
  * Validates if the assign properties are valid for a database insert
  * 
  * @return boolean true if 
  */
 public function validate()
 {
     $aFields = array('voucherTypeId' => $this->getVoucherTypeId(), 'voucherGenRuleId' => $this->getVoucherGenRuleID(), 'voucherGroupId' => $this->getVoucherGroupId(), 'voucherEnabledFrom' => $this->getEnabledFrom(), 'voucherEnabledTo' => $this->getEnabledTo(), 'voucherDescription' => $this->getDescription(), 'voucherName' => $this->getName(), 'voucherNameSlug' => $this->getSlug());
     $v = new Validator($aFields);
     $v->rule('lengthBetween', array('voucherNameSlug', 'voucherName'), 1, 100);
     $v->rule('lengthBetween', array('voucherDescription'), 1, 500);
     $v->rule('required', array('voucherNameSlug', 'voucherNameSlug', 'voucherGenRuleId', 'voucherGroupId', 'voucherEnabledFrom', 'voucherEnabledTo'));
     $v->rule('min', array('voucherTypeId', 'voucherGroupId', 'voucherGenRuleId'), 1);
     $v->rule('slug', array('voucherNameSlug'));
     $v->rule('dateBefore', array('voucherEnabledFrom'), $this->getEnabledTo());
     if ($v->validate()) {
         return true;
     } else {
         return $v->errors();
     }
 }
Exemple #26
0
 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);
 }
 /**
  * @return array
  */
 public function errors()
 {
     return $this->validator->errors();
 }
 public function testCollectFirstErrorsOnly()
 {
     $data = ["key" => ""];
     // collect the first errors only
     $v = new Validator($data);
     $v->stopOnError(true);
     $v->rule("required", ["key"])->message("is_required");
     $v->rule("equals", "key", "expected_value")->message("is_not_equals");
     $res = $v->validate();
     $errors = $v->errors();
     $this->assertEquals(1, count($errors["key"]), "it must contains only the first error");
     $this->assertEquals("is_required", $errors["key"][0], "it must contains 'is_not_equals' message");
     // collect all errors
     $v = new Validator($data);
     $v->stopOnError(false);
     // it is FALSE by default
     $v->rule("required", ["key"])->message("is_required");
     $v->rule("equals", "key", "expected_value")->message("is_not_equals");
     $res = $v->validate();
     $errors = $v->errors();
     $this->assertEquals(2, count($errors["key"]), "it must contains only the first error");
     $this->assertEquals("is_required", $errors["key"][0], "it must contains 'is_required' message");
     $this->assertEquals("is_not_equals", $errors["key"][1], "it must contains 'is_not_equals' message");
     $this->assertFalse($res);
 }
 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;
     }
 }
 /**
  * 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();
     }
 }