Thinkph6中常用的验证方式实例

我们在使用thinkphp6中的数据验证时,如果使用不多的话,会经常遇到校验不对,在这个小问题上折腾很多,索引就不用了。我还不如直接写if条件来的迅捷!!

下面把常见的校验方法进行一下整理:

php 复制代码
protected $regex = [
    'float_two' => '/^[0-9]+(.[0-9]{1,2})?$/', //两位小数点
    'phone' => '/^1[3456789]\d{9}$/', //手机号
];

    /**
     * 定义验证规则
     * 格式:'字段名'    =>    ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id'        => 'require|gt:0', //大于0
        'phone'     => 'require|regex:phone', //手机号
        'type'      => ['require', 'In:0,1,2'], //必须是0、1、2中的一个
        'order_id'      => ['require','length'=>'1,32','alphaNum'], //1-32位字母数字
        'total_price'   => ['require','float'], //金额,浮点数
        'sort'          => 'require|number', //数字
        'region_info'   => 'array', //数组
        'sort'          => 'number' //数字
        'account'       => ['require', 'alphaDash'], //字母数字下划线,破折号
        'real_name|管理员姓名' => 'require|max:16',
        'account|账号' => 'require|max:16|min:4',
        'phone|联系电话' => 'isPhone', //自定义函数
        'image|分类图片' => 'max:128',
        'is_banner|是否为Banner' => 'require|integer'
        'status|状态' => 'require|in:0,1',
        'phone' => 'require|number|mobile',
        'integral_user_give|邀请好友赠送积分' => 'require|integer|>=:0',
        'integral_community_give|发布种草可获得积分' => 'require|number|egt:0|elt:9999',
        'undelives|不配送区域信息'=>'requireIf:undelivery,1|Array|undelive', //这是哪个高手写的,这么复杂,我也没看懂
        'full_reduction|满赠金额' => 'requireIf:send_type,1|float|>=:0',
        'coupon_time|有效期限' => 'requireIf:coupon_type,0|integer|>:0',
    ];
        
    //定义不同验证的提示信息,这个很简单,一般不会出错!
     protected $message = [
        'meal_id.require'     => '请传入套餐id',
        'meal_id.number'      => '套餐id必须为数字',
        'price.require'       => '请填写套餐金额',
        'num.require'         => '请填写购买数量',
        'num.number'          => '购买数量必须为数字',
        'type.require'        => '请填写购买套餐类型'
    ];
    
    //校验手机号 , 这里的data指的是全部的参数,自定义的可以和其它参数做比较
    protected function isPhone($val,$data)
    {
        if ($val && !preg_match('/^1[3456789]{1}\d{9}$/', $val))
            return '请输入正确的手机号';
        else
            return true;
    }

    //验证场景 ,变量的方式,这里说明 login只验证密码和账号, phone只验证手机号
    protected $scene = [
        'login' => ['password', 'account'],
        'phone' => ['phone']
    ];

    //函数的方法
    public function sceneSave(){
        return $this->only(['realname','phone','address','province','city','district']);
    }

如何使用:

php 复制代码
try{
    $this->validate(TrailValidate::class)->scene('apply')->check($data);
}catch(\Exception $e){
    return app('json')->fail($e->getMessage());
}

TrailValidate::class 是你的校验类,放哪里自己定。

scene('apply') ,apply是你的场景。

check(data) ; data是你要校验的数据。

注意:验证场景有两种写法以,一种是数组,一种是函数。

当使用函数时必须是: scene+场景名(Save) 首字母大写,如果直接写场景名是识别不到的!。

以上rule汇总自多个开源系统,用来做备忘和大家共勉!

如果你有其它想法我们可以共同探讨!