Analysis of Implementation Method of Custom Verifier in thinkPHP5 Framework
- 2021-10-15 09:57:55
- OfStack
This paper describes the implementation method of thinkPHP5 framework custom verifier with an example. Share it for your reference, as follows:
The general validator manual has been very detailed, let's explain how to customize a validator
First, we set up the validata folder in the module directory
Then create a class in it, named IdMustInt. php
The code is as follows: Note that my module is named api, so the namespace is as follows
The protection attribute $rule is official and cannot be changed. In fact, the verification rule require is all encapsulated function names, so we also set up a method, and the method name can be filled in 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){
// Parameters are validation data, validation rule, all data (array), field name
// The validation data we want to judge here must be of positive integer type
if(is_numeric($value) && is_int($value+0) && ($value+0) > 0){
return true;
}else{
// If our conditions are not met, an error message is returned, which can be used in the controller getError() Method output
return $field.' Is not an integer ';
}
}
}
Next, look at the corresponding operation of our controller
public function getBanner($id)
{
// Data to be validated
$data = [
'id' => $id,
];
// Instantiate the validator
$validate = new IdMustInt();
// If there are many validation data and conditions, and all error messages need to be returned in batches, you can check() Add before $validata->batch()
$result = $validate->check($data);
if($result){
// Business logic
}else{
dump($validate->getError());
}
}
For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".
I hope this article is helpful to the PHP programming based on ThinkPHP framework.