addRule() public static method

Register new validation rule callback
public static addRule ( string $name, mixed $callback, string $message = null )
$name string
$callback mixed
$message string
 /**
  * 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]);
 }
Beispiel #2
0
 public static function validatorHook(Validator $v)
 {
     $v->addRule('testHook', function ($field, $value, array $params) {
         return false;
     });
     return $v;
 }
 function loadCustomRules()
 {
     parent::loadCustomRules();
     $this->didCustomRules = true;
     \Valitron\Validator::addRule('customRule', function ($field, $value, $params) {
         return $value === 'foo';
     }, 'values must be foo');
 }
Beispiel #4
0
 static function loadStaticRules()
 {
     if (self::$staticRulesLoaded) {
         return;
     }
     \Valitron\Validator::addRule('safeText', array('Arrow\\Options\\Validator', 'isSafeText'));
     self::$staticRulesLoaded = true;
 }
Beispiel #5
0
 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);
 }
Beispiel #6
0
 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);
 }
 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 testAddInstanceRule()
 {
     $v = new Validator(array("foo" => "bar", "fuzz" => "bazz"));
     $v->addInstanceRule("fooRule", function ($field, $value) {
         return $field !== "foo" || $value !== "barz";
     });
     Validator::addRule("fuzzerRule", function ($field, $value) {
         return $field !== "fuzz" || $value === "bazz";
     });
     $v->rule("required", array("foo", "fuzz"));
     $v->rule("fuzzerRule", "fuzz");
     $v->rule("fooRule", "foo");
     $this->assertValid($v);
 }
 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
 }
};
/**
 * 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
 *
 * @return \Slim\Flash\Messages
 */
$container['flash'] = function () {
    return new Slim\Flash\Messages();
};
 public function addNewRule($rule_name, $callback, $message)
 {
     \Valitron\Validator::addRule($rule_name, $callback, $message);
 }
Beispiel #12
0
 public function testAddRuleCallbackArrayWithArrayAsExtraParameterAndCustomMessageLabel()
 {
     $v = new Validator(array('name' => 'Chester Tester'));
     $v->labels(array('name' => 'Name'));
     $v->addRule('testRule', array($this, 'sampleObjectCallbackFalse'));
     $v->rule('testRule', 'name', array('foo', 'bar'))->message('Invalid name selected.');
     $this->assertFalse($v->validate());
 }
Beispiel #13
-1
function validate(&$data)
{
    $v = new \Valitron\Validator($data);
    // required
    $v->rule('required', 'first_name')->message('First Name is required.');
    $v->rule('required', 'last_name')->message('Last Name is required.');
    $v->rule('required', 'email')->message('Email Addres is required.');
    $v->rule('required', 'phone')->message('Phone Number is required.');
    $v->rule('required', 'shipping_address1')->message('Shipping Address1 is required.');
    $v->rule('required', 'shipping_city')->message('Shipping City is required.');
    $v->rule('required', 'shipping_state')->message('Shipping State is required.');
    $v->rule('required', 'shipping_zip_code')->message('Shipping Zip Code is required.');
    $v->rule('required', 'cc_number')->message('Credit Card Number is required.');
    $v->rule('required', 'cc_exp_month')->message('Credit Card Expiration Month is required.');
    $v->rule('required', 'cc_exp_year')->message('Credit Card Expiration Year is required.');
    $v->rule('required', 'cc_cvv')->message('Credit Card CVV is required.');
    // personal
    $v->rule('regex', 'first_name', '/^[A-Z \'.-]{2,30}$/i')->message('First Name contains invalid characters.');
    $v->rule('regex', 'last_name', '/^[A-Z \'.-]{2,40}$/i')->message('Last Name contains invalid characters.');
    $v->rule('email', 'email')->message('Email Address is not a valid email address.');
    $v->rule('max', 'email', 80)->message('Email Address must be less than 80 characters.');
    $v->rule('regex', 'phone', '/\\(?\\d{3}\\)?[-\\s.]?\\d{3}[-\\s.]\\d{4}/x')->message('Phone Number contains invalid characters.');
    // $v->rule('regex', 'phone', '/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/')->message('Phone Number contains invalid characters.');
    // shipping
    $v->rule('regex', 'shipping_address1', '/^[A-Z0-9 \',.#-]{2,80}$/i')->message('Shipping Address1 contains invalid characters.');
    if (!empty($data['shipping_address2'])) {
        $v->rule('regex', 'shipping_address2', '/^[A-Z0-9 \',.#-]{2,80}$/i')->message('Shipping Address2 contains invalid characters.');
    }
    $v->rule('regex', 'shipping_city', '/^[A-Z \'.-]{2,60}$/i')->message('Shipping City contains invalid characters.');
    $v->rule('regex', 'shipping_state', '/^[A-Z]{2}$/')->message('Shipping State contains invalid characters.');
    $v->rule('regex', 'shipping_zip_code', '/^(\\d{5}$)|(^\\d{5}-\\d{4})$/')->message('Shipping Zip Code contains invalid characters.');
    // billing
    $data['cc_number'] = str_replace(array(' ', '-'), '', $data['cc_number']);
    \Valitron\Validator::addRule('creditCard', function ($field, $value, array $params) {
        if (!preg_match('/^4[0-9]{12}(?:[0-9]{3})?$/', $value) && !preg_match('/^5[1-5][0-9]{14}$/', $value) && !preg_match('/^3[47][0-9]{13}$/', $value) && !preg_match('/^6(?:011|5[0-9]{2})[0-9]{12}$/', $value)) {
            return false;
        } else {
            return true;
        }
    }, 'Credit Card Number contains invalid characters.');
    \Valitron\Validator::addRule('expirationYear', function ($field, $value, array $params) {
        if ($value < date('Y')) {
            return false;
        } else {
            return true;
        }
    }, 'Credit Card Expiration Year must be a date after ' . date('Y') . '.');
    $v->rule('creditCard', 'cc_number')->message('Credit Card Number contains invalid characters.');
    $v->rule('min', 'cc_exp_month', 1)->message('Credit Card Expiration Month must be greater than 1.');
    $v->rule('max', 'cc_exp_month', 12)->message('Credit Card Expiration Month must be less than 12.');
    $v->rule('expirationYear', 'cc_exp_year')->message('Credit Card Expiration Year must be a date after ' . date('Y'));
    $v->rule('regex', 'cc_cvv', '/^[0-9]{3,4}$/')->message('Credit Card CVV contains invalid characters.');
    if (empty($data['use_same_address'])) {
        $v->rule('required', 'billing_address1')->message('Billing Address1 is required.');
        $v->rule('required', 'billing_city')->message('Billing City is required.');
        $v->rule('required', 'billing_state')->message('Billing State is required.');
        $v->rule('required', 'billing_zip_code')->message('Billing Zip Code is required.');
        $v->rule('regex', 'billing_address1', '/^[A-Z0-9 \',.#-]{2,80}$/i')->message('Billing Address1 contains invalid characters.');
        if (!empty($data['billing_address2'])) {
            $v->rule('regex', 'billing_address2', '/^[A-Z0-9 \',.#-]{2,80}$/i')->message('Billing Address2 contains invalid characters.');
        }
        $v->rule('regex', 'billing_city', '/^[A-Z \'.-]{2,60}$/i')->message('Billing City contains invalid characters.');
        $v->rule('regex', 'billing_state', '/^[A-Z]{2}$/')->message('Billing State contains invalid characters.');
        $v->rule('regex', 'billing_zip_code', '/^(\\d{5}$)|(^\\d{5}-\\d{4})$/')->message('Billing Zip Code contains invalid characters.');
    }
    if ($v->validate()) {
        return null;
    } else {
        return $v->errors();
    }
}