This article describes the implementation method of the custom validator of thinkPHP5 framework. Share it for your reference, as follows:
The ordinary validator manual is already very detailed, let’s explain how to customize a validator
First, we create a validat folder in the module directory
Then create a class inside, named
The code is as follows: Note that my module is named api, so the namespace is as follows
The protection attribute $rule is an official regulation and cannot be changed. In fact, the verification rules require are all encapsulated function names, so we also establish a method, and the method name can be filled in after the verification rules.
namespace app\api\validate; use think\Validate; class IdMustInt extends Validate { protected $rule = [ 'id' => 'require|IsInt' ]; protected function IsInt($value,$rule,$data,$field){ //The parameters are verification data, verification rules, all data (array), and field names in turn //The verification data requirements we want to judge here must be positive integer if(is_numeric($value) && is_int($value+0) && ($value+0) > 0){ return true; }else{ //If our conditions do not meet, return an error message. You can use the getError() method to output it in the controller return $field.'Not an integer'; } } }
Next, let’s take a look at the corresponding operations of our controller
public function getBanner($id) { //Data that needs to be verified $data = [ 'id' => $id, ]; //Instantiate the validator $validate = new IdMustInt(); //If there are many verification data and many conditions, and all error messages need to be returned in batches, you can add $validata->batch() before check() $result = $validate->check($data); if($result){ //Business Logic }else{ dump($validate->getError()); } }
For more information about thinkPHP, please visit the special topic of this site:ThinkPHP Introduction Tutorial》、《Summary of the operation skills of thinkPHP templates》、《Summary of common methods of ThinkPHP》、《Codeigniter Introductory Tutorial》、《Advanced tutorial on CI (CodeIgniter) framework》、《Zend FrameWork framework tutorial"and"PHP template technical summary》。
I hope that the description in this article will be helpful to everyone's PHP programming based on the ThinkPHP framework.