学习thinkphp5.0验证类使用方法

yipeiwu_com6年前PHP代码库

通过一个实例,给大家讲解一下如果通过thinkphp5.0验证类的方法。

自定义验证类,需继承Validate类

比如在home模块新建validate文件夹,再新建Test.php验证类,内容如下:

<?php
namespace app\home\validate;
use think\Validate;
class Test extends Validate
{
  protected $rule = [
    'name' => 'require|regex:/.{6}/',
    'age' => 'number|between:1,120',
    'email' => 'email'
  ];
  protected $message = [
    'name.require' => 'name不能少',
    'name.regex' => 'name不能少于6个字符',
    'age.number' => 'age必须是数字',
    'age.between' => 'age必须在1到120之间',
    'email.email' => 'email格式不对',
  ];
  protected $scene = [
    'name_email' => ['name','email'],
  ];
}
?>

在Index控制器test方法使用

<?php
namespace app\home\controller;
use think\Loader;
use think\Controller;
class Index extends Controller
{
  public function test(){
    $date = [
      'name'=>'qw2e',
      'email'=>'12313'
    ];
    //$validate = Loader::validate('Test');//使用加载类Loader
    $validate = validate('Test');//使用助手函数
    $result = $validate->scene('name_email')->check($date);
    if(!$result){
      dump($validate->getError());
    }
  }
}

以上就是我们给出的验证类的实例方法,如果还有哪里不明白,大家可以在下方留言一起讨论。

相关文章

PHP函数checkdnsrr用法详解(Windows平台用法)

本文实例讲述了PHP函数checkdnsrr用法。分享给大家供大家参考,具体如下: 在php.net上是这样说的: (PHP 4, PHP 5) checkdnsrr — Check D...

PHP使用finfo_file()函数检测上传图片类型的实现方法

本文实例讲述了PHP使用finfo_file()函数检测上传图片类型的实现方法。分享给大家供大家参考,具体如下: 在输入输出中,文件的交互必不可少,比如文件的上传什么的。这里我们来解决一...

最常用的8款PHP调试工具

Web 开发并不是一项轻松的任务,有超级多服务端脚本语言提供给开发者,但是当前 PHP 因为具有额外的一些强大的功能而越来越流行。PHP 是最强大的服务端脚本语言之一,同时也是 Web...

PHP使用curl模拟post上传及接收文件的方法

本文实例讲述了PHP使用curl模拟post上传及接收文件的方法。分享给大家供大家参考,具体如下: public function Action_Upload(){ $th...

PHP CURL函数库第1/2页

curl_close — 关闭一个curl会话 curl_copy_handle — 拷贝一个curl连接资源的所有内容和参数 curl_errno — 返回一个包含当前会话错误信息的数...