DEV Community

vic
vic

Posted on • Edited 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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more