validate

时间:2022-10-12 15:15:17

<?php

$rules = [
"ip" => function ($var) {return ip2long($var);},
"email" => function ($var) {return filter_var($var, FILTER_VALIDATE_EMAIL);},
"username" => function ($var) {return preg_match("/^[a-zA-Z0-9]*$/", $var);},
"password" => function ($var) {return (strlen($var) <= 30) ? true : false;},
"mobile" => function ($var) {return preg_match("/^\d{3}\d?-?\d{10}$/", $var);},
"cid" => function ($var) {return preg_match("/^[1-9][0-9]{16}[0-9xX]$/", $var);},
"number" => function ($var) {return is_numeric($var);},
"int" => function ($var) {return is_numeric($var) ? (preg_match("/[.ex]/", strval($var)) ? false : true):fasle;},
"string" => function ($var) {return is_string($var);},
"time" => function ($var) {return strtotime($var);},
"url" => function ($var) {return preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $var);},
"strrange" => function ($var) {global $_rngstart, $_rngend;return (strlen($var) >= $_rngstart && strlen($var) <= $_rngend) ? true : false;},
"numrange" => function ($var) {global $_rngstart, $_rngend;return ($var >= $_rngstart && $var <= $_rngend) ? true : false;},
"required" => function ($var) {return is_null($var) ? false : true;},
];
$gValidateErrs = [];
$_rngstart = 0;
$_rngend = 0;
function fnvalidate($filter, $input) {
global $rules, $gValidateErrs, $_rngstart, $_rngend;
foreach ($filter as $k => $v) {
if (is_string($v)) {
if (preg_match_all("/strrange\((\d*)\s?,\s?(\d*)\)/", $v, $matches)) {
$_rngstart = $matches[1][0];
$_rngend = $matches[2][0];
} elseif (preg_match_all("/numrange\((\d*)\s?,\s?(\d*)\)/", $v, $matches)) {
$_rngstart = $matches[1][0];
$_rngend = $matches[2][0];
}
$v = preg_replace("/\(.*?\)/", "", $v);
$rls = explode(" ", $v);
if (in_array("required", $rls)) {
if (isset($input[$k])) {
foreach ($rls as $r) {
if (!$rules[$r]($input[$k])) {
array_push($gValidateErrs, [$k, $r]);
}
}
} else {
array_push($gValidateErrs, [$k, "required"]);
}
} else {
if (isset($input[$k])) {
foreach ($rls as $r) {
if (!$rules[$r]($input[$k])) {
unset($input[$k]);
}
}
}
}
} else {
if (is_array($v)) {
fnvalidate($v, $input[$k]);
} else {
if (is_callable($v)) {
$v($input[$k]);
}
}
}
}
}
//test;
$filter = [
"p" => "numrange(1,7) int required",
"q" => [
"q1" => "numrange(5,8) int required",
],
];
$input = [
"p" => 0,
"q" => ["q1" => 6],
];

//test
fnvalidate($filter, $input);

?>