自用驗證類封裝

h6play發表於2020-12-02
class Validate
{
    public $rules = [];
    public $message = [];

    public function __construct()
    {
        Validator::extend("empty", function($attribute, $value, $parameters, $validator) {
            return true;
        });
        Validator::extend("arr", function($attribute, $value, $parameters, $validator) {
            if(isset($parameters[0])) {
                switch ($parameters[0]) {
                    case "int":
                        return !array_filter($value, function ($v) { return !is_integer($v); });
                    case "number":
                        return !array_filter($value, function ($v) { return !is_numeric($v); });
                    case "bool":
                        return !array_filter($value, function ($v) { return !is_bool($v); });
                    case "string":
                        return !array_filter($value, function ($v) { return !is_string($v); });
                    default:
                        return is_array($value);
                }
            }
            return is_array($value);
        });
    }

    public static function M($p = null) {
        if($p === null) {
            $p = Request::all();
        }
        $v1 = new static;
        $v2 = Validator::make($p, $v1->rules, $v1->message);
        if($v2->fails()) {
            throw new ParamException($v2->errors()->first());
        }
        return $v2->validate();
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章