Home > Backend Development > PHP Tutorial > Specific use of ThinkPHP5 validator

Specific use of ThinkPHP5 validator

不言
Release: 2023-03-28 17:46:01
Original
3128 people have browsed it

This article mainly introduces the specific use of ThinkPHP5 validator, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Foreword:

When we are doing API development, we will accept parameters from the client. Everyone knows that this parameter is not trustworthy. Our back-end developers must verify this parameter. . I only knew about the tp5 validator in previous development, but I didn't know its purpose, because the previous development verification was often based on model fields. The validator is more suitable for API development. Today I will briefly talk about the use of the validator

Directory:

  1. Create a validator

  2. Write a separate validator

  3. Call verification

1. Create a validator

First we need a folder to store our validator. We create a folder at the same level as the controller under the module and name it validate

Then we can create the validator. We only need to create a class and inherit the validate class of tp5.

But friends who are familiar with object-oriented thinking must know that when we need a method that must be used by every validator, but do not modify the source code of tp5. We will write one more class as our base class. All validators inherit this base class, and then this base class inherits the validate class of tp5.

Here we name it baseValidate

Now let’s create a serious validator. For example:

namespace app\index\validate;

use think\Validate;

class User extends Validate
{
  protected $rule = [
    'name' => 'require|max:25',
    'email' => 'email',
  ];

}
Copy after login

Then instantiate it in the controller or model and then call

//虚拟一组数据,实际开发中是接受用户传递的数据
$data = [
  'name'=>'thinkphp',
  'email'=>'thinkphp@qq.com'
];

$validate = Loader::validate('User');

if(!$validate->check($data)){
  dump($validate->getError());
}
Copy after login

The application of such a validator is now written. Let's see if there's anything we can simplify.

  1. First of all, the data that needs to be verified is what we receive from the client. Then, the first step is to accept the data

  2. Then we have to The data is verified. If the verification fails, the error message

is returned. These two steps are performed every time the interface is requested. Then we want to encapsulate this into BaseValidate

namespace app\home\validate;
use think\Exception;
use think\Request;
use think\Validate;
class BaseValidate extends Validate
{
  public function goCheck($data='')
  {
    //实例化请求对象
    $requestObj=Request::instance();
    //如果传入为空则获取请求里的参数
    empty($data)&&$data=$requestObj->param();
    if ($this->check($data)) {
      //如果验证通过了
      return true;
    }else{
      //如果验证没通过
      $error=$this->getError();
      //抛出异常
      throw new Exception($error);
    }
  }
}
Copy after login

After the goCheck method is encapsulated, someone may ask, where is the verification rule? Woolen cloth?

2. Write a separate validator

#I have said before that BaseValidate is used to be inherited, so for the real validator, we also Didn't start writing. The rules are formulated into this validator. For a deeper understanding, here is an example using custom validation rules. In fact, the verification rules written by tp should be sufficient.

Let’s take the most commonly accepted data as an example, which is id. Normally, this id represents the id of a certain piece of data in our database. We often design this id as an unsigned auto-incrementing primary key, which is translated into human language as a positive integer. Then if the parameter passed by the customer is a negative number or a decimal, it should not pass the verification.

We create a validator based on the above requirements. The location is still the same as before in the validate folder

and is named IdMustBePositiveInt.php (the name is a bit long, but fortunately the text is clear)

First of all, we must inherit our basic validator

class IdMustBePositiveInt extends BaseValidate
Copy after login

and then formulate rules to assign a value to a fixed member variable

  protected $rule = [
  //require是内置规则,而tp5并没有正整数的规则,所以下面这个positiveInt使用自定义的规则
    'id' => 'require|positiveInt'
  ];
Copy after login

So how to do custom rules? It’s actually simple. Define a protected method

//系统会自动传入几个参数 第一个是 要验证的值,第二个是规则,自己可以规定规则内容或者不写,第三个是最初传入的data。其实不只这三个参数,想了解详细的可以看看文档
 protected function positiveInt($value, $rule='', $data)
  {
    if (is_int(($value+0))&&($value+0)>0) {
      return true;
    }else{
      return 'id必须为正整数';
    }
  }
Copy after login

! ! Note: If the judgment fails here: the return is not false but an error message.

3. Call verification

According to our previous encapsulation, the effect we need to achieve is to accept parameters and verify the parameters as one. So now how do we call verification?

Here comes the awesome one, let’s take ID as an example

 public function test($id)
  {
    //在控制器中直接调用写上这行代码就搞定验证了
    (new IdMustBePositiveInt)->goCheck();
  }
Copy after login

  1. ##Just this one line of code can directly complete the verification. When we instantiate the id validator, we call the goCheck method of its parent class.

  2. The goCheck method will accept parameters and pass the parameters into the check method on the validate object

  3. will match what we have in the id validator The require rules specified in $rule and our custom rules.

  4. If all pass, it will return true

  5. If one of them does not match, an exception will be thrown

这次只举了id为例子,虽然看上去比直接写独立验证麻烦很多,但是大家仔细想想,这个验证规则其实在很多地方都是一样的,比如密码验证规则,用户名验证规则等,当这个项目写完了。你已经完成了很多验证器。其实在下个项目中还可以继续套用的哦

TP5验证规则使用

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

// 日期格式验证
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
Copy after login

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

$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());
}
Copy after login

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

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

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

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

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

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

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

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

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

好了,本次tp5验证器的介绍了就写到这里了,希望对大家的学习有所帮助。

相关推荐:

ThinkPHP5.0框架控制器继承基与自定义类案例详解

Thinkphp5 前置操作详解

The above is the detailed content of Specific use of ThinkPHP5 validator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template