zoukankan      html  css  js  c++  java
  • TP5验证规则使用

    TP5验证规则使用

     

    定义验证器类:

    namespace appindexvalidate;
    use thinkValidate;
    class User extends Validate
    {
        protected $rule = [
            'name'  =>  'require|max:25',
            'email' =>  'email',
        ];
    
        protected $message = [
            'name.require'  =>  '用户名必须',
            'email' =>  '邮箱格式错误',
        ];
    
        protected $scene = [
            'add'   =>  ['name','email'],
            'edit'  =>  ['email'],
        ];    
    }
     

    ①静态调用(使用内置的规则验证单个数据,返回值为布尔值

    // 日期格式验证
    Validate::dateFormat('2016-03-09','Y-m-d'); // true
    // 验证是否有效的日期
    Validate::is('2016-06-03','date'); // true
    // 验证是否有效邮箱地址
    Validate::is('thinkphp@qq.com','email'); // true
    // 验证是否在某个范围
    Validate::in('a',['a','b','c']); // true
    // 验证是否大于某个值
    Validate::gt(10,8); // true
    // 正则验证
    Validate::regex(100,'d+'); // true

    ②模型验证(在模型中的验证方式

    $User = new User;
    $result = $User->validate(
        [
            'name'  => 'require|max:25',
            'email'   => 'email',
        ],
        [
            'name.require' => '名称必须',
            'name.max'     => '名称最多不能超过25个字符',
            'email'        => '邮箱格式错误',
        ]
    )->save($data);
    if(false === $result){
        // 验证失败 输出错误信息
        dump($User->getError());
    }

    ③控制器验证(控制器中进行验证

    如果你需要在控制器中进行验证,并且继承了 hinkController的话,可以调用控制器类提供的validate方法进行验证,如下:

    $result = $this->validate(
        [
            'name'  => 'thinkphp',
            'email' => 'thinkphp@qq.com',
        ],
        [
            'name'  => 'require|max:25',
            'email'   => 'email',
        ]);
    if(true !== $result){
        // 验证失败 输出错误信息
        dump($result);
    }

    控制器中的验证代码可以简化为:

    $result = $this->validate($data,'User');
    if(true !== $result){
        // 验证失败 输出错误信息
        dump($result);
    }

    如果要使用场景,可以使用:

    $result = $this->validate($data,'User.edit');
    if(true !== $result){
        // 验证失败 输出错误信息
        dump($result);
    }

    在validate方法中还支持做一些前置的操作回调,使用方式如下:

    $result = $this->validate($data,'User.edit',[],[$this,'some']);
    if(true !== $result){
        // 验证失败 输出错误信息
        dump($result);
    }
  • 相关阅读:
    for of 与 for in的区别
    Mac Item2 SSH免密登录Linux 服务器的两种方式
    组塞式,非阻塞式,同步异步
    Thrift_简介(基于C#)
    HTTP Error 500.22
    http协议
    IIS_部署出错
    JavaScript如何实现继承
    $(function(){})与 (function(){})() (function($){})() 的区别
    C#_反射机制
  • 原文地址:https://www.cnblogs.com/my2018/p/9944389.html
Copyright © 2011-2022 走看看