A simple parameter validator
vic
Posted on May 19, 2021
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
//)
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'
]);
Can be used here
https://github.com/lizhichao/one
đź’– đź’Ş đź™… đźš©
vic
Posted on May 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.