php-tp5的validate自动验证

景仲渊
2023-12-01

以前都是自己写代码验证,学学tp5自带的验证功能。


首先使用验证器验证,在模块目录下,建一个validate目录,在其下面自定义要使用的验证器,并让它extends 框架的Validate类:

<?php
namespace app\admin\validate;

use think\Validate;

class User extends Validate{
    protected $rule = [
        'user_name'  => 'require|max:20',
        'password'  => 'require',
        'real_name'  => 'require|max:12',
        'email' => 'email',
        'qq'    => 'max:20',
        'phone'    => 'require|length:11',
    ];
}

这样我们就有了一个针对user使用的自动验证器,我们将要验证的字段,给他定义好对应的规则。

这里注意:框架本身自带的很多规则及其提示信息,直接调用就好,如果不满足需求,还支持自定义规则。

贴出框架源代码:

// 验证规则默认提示信息
protected static $typeMsg = [
    'require'     => ':attribute require',
    'number'      => ':attribute must be numeric',
    'integer'     => ':attribute must be integer',
    'float'       => ':attribute must be float',
    'boolean'     => ':attribute must be bool',
    'email'       => ':attribute not a valid email address',
    'mobile'      => ':attribute not a valid mobile',
    'array'       => ':attribute must be a array',
    'accepted'    => ':attribute must be yes,on or 1',
    'date'        => ':attribute not a valid datetime',
    'file'        => ':attribute not a valid file',
    'image'       => ':attribute not a valid image',
    'alpha'       => ':attribute must be alpha',
    'alphaNum'    => ':attribute must be alpha-numeric',
    'alphaDash'   => ':attribute must be alpha-numeric, dash, underscore',
    'activeUrl'   => ':attribute not a valid domain or ip',
    'chs'         => ':attribute must be chinese',
    'chsAlpha'    => ':attribute must be chinese or alpha',
    'chsAlphaNum' => ':attribute must be chinese,alpha-numeric',
    'chsDash'     => ':attribute must be chinese,alpha-numeric,underscore, dash',
    'url'         => ':attribute not a valid url',
    'ip'          => ':attribute not a valid ip',
    'dateFormat'  => ':attribute must be dateFormat of :rule',
    'in'          => ':attribute must be in :rule',
    'notIn'       => ':attribute be notin :rule',
    'between'     => ':attribute must between :1 - :2',
    'notBetween'  => ':attribute not between :1 - :2',
    'length'      => 'size of :attribute must be :rule',
    'max'         => 'max size of :attribute must be :rule',
    'min'         => 'min size of :attribute must be :rule',
    'after'       => ':attribute cannot be less than :rule',
    'before'      => ':attribute cannot exceed :rule',
    'expire'      => ':attribute not within :rule',
    'allowIp'     => 'access IP is not allowed',
    'denyIp'      => 'access IP denied',
    'confirm'     => ':attribute out of accord with :2',
    'different'   => ':attribute cannot be same with :2',
    'egt'         => ':attribute must greater than or equal :rule',
    'gt'          => ':attribute must greater than :rule',
    'elt'         => ':attribute must less than or equal :rule',
    'lt'          => ':attribute must less than :rule',
    'eq'          => ':attribute must equal :rule',
    'unique'      => ':attribute has exists',
    'regex'       => ':attribute not conform to the rules',
    'method'      => 'invalid Request method',
    'token'       => 'invalid token',
    'fileSize'    => 'filesize not match',
    'fileExt'     => 'extensions to upload is not allowed',
    'fileMime'    => 'mimetype to upload is not allowed',
];

我也没一个一个试额。


验证器有了,接下来就要使用了哈,嗯,文档中叫验证情景,不对,是场景:

我是在user控制器中验证,所以我写在控制器中:

$validate = Loader::validate('User');
if(!$validate->check($data)){
    dump($validate->getError());
}else{
    dump($data);
}
加载自定义好的验证器,然后使用check()方法。对传入的数据进行验证。失败则获取error,成功则输出!

当然,tp5提供一个实例化验证器的助手函数:

$validate = validate("User");
我不喜欢用助手函数,不过功能实现就好。


不使用验证器,直接在场景使用时定义规则,就是独立验证。

在实例化validate对象的时候,传入你定义的规则即可,也可以使用rule()方法定义。写法不同罢了。

同样,上面所用的采用'|'来添加多个规则的写法,也可以改为数组的方法,数组无处不在。。。


如果要改变提示信息,也可以在验证器中自定义:

<?php
namespace app\admin\validate;

use think\Validate;

class User extends Validate{
    protected $rule = [
        'user_name'  => 'require|max:20',
        'password'  => 'require',
        'real_name'  => 'require|max:12',
        'email' => 'email',
        'qq'    => 'number|max:20',
        'phone'    => 'require|length:11|number',
    ];

    protected $message  =   [
        'user_name.require' => '名称必须',
        'user_name.max'     => '名称最多不能超过25个字符',
        'qq.number'   => 'qq必须是数字',
        'phone.number'   => '手机必须是数字',
        'phone.max'   => '请输入11位手机号',
        'email'        => '邮箱格式错误',
    ];

}


控制器中使用批量验证的话,我木有试额,批量验证不通过返回的是一个错误数组:

  1. $validate = new Validate($rule, $msg);
  2. $result = $validate->batch()->check($data);

上面一直使用的是框架自带的规则,定义验证规则:

1、使用了验证器的话,只要在类中,定义函数

'user_name'  => 'require|max:20|checkName:xinghua',
自定义一个checkName规则:

// 自定义验证规则
protected function checkName($value,$rule,$data){
    return $rule == $value ? true : '名称必须是xinghua';
}
定义的规则名不能和已有的冲突哦;

2、没使用验证器的话,采用extend()方法定义

$validate->extend('checkName', function ($value, $rule) {

 return $rule == $value ? true : '名称错误';

});

还支持批量注册规则,同样是使用数组。


定义字段信息,可以给对应的字段添加描述:

protected $field = [
    'user_name'  => '用户名',
    'password'  => '密码',
    'real_name'  => '姓名',
    'email' => '邮箱',
    'qq'    => 'QQ',
    'phone'    => '手机'
];

在使用场景中,直接定义字段,来限制当前验证的字段。

在验证器中定义$scene:

protected $scene = [
    'register' => ['user_name','real_name','password','phone','email'],
];
场景使用时,就需要加上scene()方法:

$validate->scene('register')->check($data)

显然,我没把qq字段写进去,设定的qq验证规则木有生效。

在scene里还可以重写规则,

protected $scene = [

'edit' => ['name','age'=>'require|number|between:1,120'],

];

动态设置的话采用匿名函数:$validate->scene('edit', function($key,$data){

return 'email'==$key && isset($data['id'])? true : false;

});




END;







 类似资料: