About the implementation method of custom validator in thinkPHP5 framework

不言
Release: 2023-04-01 14:06:02
Original
2265 people have browsed it

This article mainly introduces the implementation method of the thinkPHP5 framework custom validator, and analyzes the specific definition and usage of thinkPHP custom validator in the form of examples. Friends in need can refer to the following

The examples of this article are described Developed the thinkPHP5 framework custom validator implementation method. Share it with everyone for your reference, the details are as follows:

The ordinary validator manual is very detailed, let’s explain how to customize a validator

First we create the validata file in the module directory Folder

Then create a class in it and name it IdMustInt.php

The code is as follows: Note that my module is called api, so the namespace is as follows

Protect attributes $rule is an official rule and cannot be changed. In fact, the verification rules require are all encapsulated function names, so we also create a method and fill in the method name after the verification rule

namespace app\api\validate;
use think\Validate;
class IdMustInt extends Validate
{
  protected $rule = [
    'id' => 'require|IsInt'
  ];
  protected function IsInt($value,$rule,$data,$field){
  //参数依次为验证数据,验证规则,全部数据(数组),字段名
  //这里我们要判断的验证的数据要求必须为正整型
    if(is_numeric($value) && is_int($value+0) && ($value+0) > 0){
      return true;
    }else{
  //如果不符合我们的条件,返回错误信息,在控制器中可以用getError()方法输出
      return $field.'不是整型';
    }
  }
}
Copy after login

Let’s look at the corresponding operations of our controller

public function getBanner($id)
{
    //需要验证的数据
    $data = [
      'id' => $id,
    ];
  //实例化验证器
    $validate = new IdMustInt();
  //如果验证数据较多,条件也较多,需要批量返回所有错误信息的话,可以在check()前加上$validata->batch()
    $result = $validate->check($data);
    if($result){
      //业务逻辑
    }else{
      dump($validate->getError());
    }
}
Copy after login

##The above is the entire content of this article, I hope it will be helpful to everyone Learning will be helpful. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About thinkphp’s method of implementing the browsing history function

About ThinkPHP’s controller analysis

The above is the detailed content of About the implementation method of custom validator in thinkPHP5 framework. 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