Houze 文档 / 基础组件 / 验证器

基础组件

验证器

验证器负责「把请求参数按规则过一遍」,规则用字符串声明,支持场景切换与批量校验。

用法

use houze\Validate;

class ArticleValidate extends Validate
{
    protected $rule = [
        'title'   => 'require|max:80',
        'content' => 'require',
        'type_id' => 'require|int',
    ];

    protected $message = [
        'title.require'   => '标题不能为空',
        'title.max'       => '标题最多 80 个字',
        'type_id.require' => '请选择分类',
    ];

    protected $scene = [
        'add'  => ['title', 'content', 'type_id'],
        'edit' => ['title'],
    ];
}

在控制器里调

$validate = new \app\validate\ArticleValidate();
$ok = $validate->scene('add')
               ->data(\houze\Request::post())
               ->fails();

if ($ok) {
    // fails() 返回 true 表示「校验失败」
    return $this->api(422, $validate->errors()[0]);
}

注意语义:fails() 为 true 才是失败,容易看反。

可用规则

require accepted number int float bool array
email mobile phone date alpha alphanum alphadash chs chsalpha chsalphanum
cntrl graph print lower upper space xdigit url ip dateformat idcard
licenseplate macaddr zip in notin between notbetween max min after before
expire confirm different eq neq egt gt elt lt username password longlat
get post ajax jwt csrf status message

带参数的写法是冒号,如 'age' => 'between:1,120'、'type' => 'in:1,2,3'。

几种常用组合

'username' => 'require|alpha|length:4,20',
'password' => 'require|length:8,32',
'repassword' => 'require|confirm:password',
'email'    => 'email',
'mobile'   => 'mobile',
'start'    => 'date|before:end',

要点

  • batch(true) 一次收集全部错误,默认遇到第一个错就返回;
  • 校验失败会触发 Lifecycle::validate_error(),可统一转成 JSON 响应;
  • 验证器只管格式,业务规则(比如「分类不存在」)仍要在控制器里查库判断。

最后更新:2026-12-02 · 本文档对应 Houze v2.5.9,如有出入以框架源码为准。