rule() 공개 메소드

Convenience method to add a single validation rule
public rule ( string | callback $rule, array $fields )
$rule string | callback
$fields array
 /**
  * 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]);
 }
예제 #2
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);
 }
예제 #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()];
}
예제 #4
0
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()];
}
예제 #5
0
 /**
  * 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;
 }
예제 #6
0
 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);
 }
예제 #7
0
파일: BMR.php 프로젝트: BenHicksy/dietddocs
 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);
 }
예제 #8
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());
     }
 }
예제 #9
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;
 }
예제 #10
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);
     }
 }
예제 #11
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;
     }
 }
예제 #12
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;
     }
 }
예제 #13
0
 /**
  * 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);
 }
예제 #14
0
use MonCompte\LdapSync;
use MonCompte\Format;
use Valitron\Validator;
function getArrayValue($array, $key)
{
    if (!isset($array[$key])) {
        $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']);
예제 #15
0
 public function testInstanceOfInvalidWithString()
 {
     $v = new Validator(array('attributeName' => new stdClass()));
     $v->rule('instanceOf', 'attributeName', 'SomeOtherClass');
     $this->assertFalse($v->validate());
 }
예제 #16
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());
 }
예제 #17
0
 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);
 }
예제 #18
0
 /**
  * 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();
     }
 }
 * @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
 *
 * @return \Slim\Flash\Messages
 */
$container['flash'] = function () {
    return new Slim\Flash\Messages();
};
/**
 * Setup cloudinary config before view
 */
Cloudinary::config($container->get('settings')['cloudinary']);
예제 #20
0
 /**
  * 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();
     }
 }
예제 #21
0
 /**
  * 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();
     }
 }
예제 #22
0
 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);
     }
 }
예제 #23
0
 public function testOptionalNotProvided()
 {
     $v = new Validator(array());
     $v->rule('optional', 'address')->rule('email', 'address');
     $this->assertTrue($v->validate());
 }
예제 #24
0
 /**
  * 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();
     }
 }
예제 #25
0
 public function testIfNotSetIsNotSetNotProvided()
 {
     $v = new Validator(array('firstname' => 'Daniel'));
     $v->rule('ifNotSet', 'name', array('rule' => 'required', 'field' => 'lastname'));
     $this->assertFalse($v->validate());
 }
 /**
  * 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;
 }
예제 #27
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());
 }
 public function testAddRuleWithNamedCallbackErr()
 {
     $v = new Validator(array("foo" => "bar"));
     $v->rule("callbackTestFunction", "foo");
     $this->assertTrue($v->validate());
 }
예제 #29
0
 /**
  * @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;
     }
 }