DEV Community

vic
vic

Posted on • Updated on

A simple parameter validator

A simple parameter validator

$_POST  = [
    'email' => 'xxxx',
    'age'   => 2
];
$vt     = new Validator();
$result = $vt->validate($_POST, [
    'name'  => 'required|min_len:5|max_len:10', // required 5<= strlen(name) <=10
    'email' => 'required|email', // required email
    'age'   => 'uint|min:18|max:200'  // options Positive integer 18<= age <=200
])->isOk();

if ($result === false) {
    print_r($vt->getErrs());
}


//Array
//(
//    [0] => name can not be empty
//    [1] => email incorrect format
//    [2] => age not less than 18
//)

Enter fullscreen mode Exit fullscreen mode

Built-in rules

  • required
  • numeric numbers include floating point numbers
  • min cannot be less than
  • max cannot be greater than
  • min_len cannot be shorter than
  • max_len cannot be longer than
  • int integer
  • uint positive integer
  • email mailbox format
  • ip ip format
  • stop prevents bubbling (when a rule is not met, the remaining rules are not verified)

If not enough? Customizable rules

$vt->addRule('between', [
    'msg' => ':attribute can only be between :arg1-:arg2',
    'fn'  => function ($value, $arg1, $arg2) {
        return $value >= $arg1 && $value <= $arg2;
    }
]);

$vt->validate(['a' => 10], [
    'a' => 'required|between:3,10'
]);

// Check whether a value exists in the database
$vt->addRule('exist', [
    'msg' => 'the :attribute already exists',
    'fn'  => function ($value, $table, $filed) {
        return Model::from($table)->where($filed,$value)->find() !== null;
    }
]);

$vt->validate(['email' => 'sss@ss.com'], [
    'email' => 'required|exist:users,email'
]);
Enter fullscreen mode Exit fullscreen mode

Can be used here
https://github.com/lizhichao/one

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair
[
    'name'  => 'required|min_len:5,max_len:10', // required 5<= strlen(name) <=10
    'email' => 'required|email', // required email
    'age'   => 'uint|min:18|max:200' 
]
Enter fullscreen mode Exit fullscreen mode

What's the difference between using a comma as a separator and a pipe here?

Collapse
 
lizhichao profile image
vic

Thanks for the feedback, it should be all pipe symbols, the article is wrong