This article mainly introduces the implementation method of THINKPHP5 framework custom validator, and analyzes the specific definition and use method of thinkphp custom validator with the example form, the friend who needs can refer to the following
This paper describes the implementation method of THINKPHP5 framework custom Validator. Share to everyone for your reference, as follows:
The General Validator Manual is already detailed, so let's explain how to customize a validator
First we create the Validata folder in the module directory
Then build 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
Protection attribute $rule is official, can not change, in fact, the validation rules require are encapsulated function name, so we also set up a method, the method name is filled in after the validation rules can be
Namespace App\api\validate;use think\validate;class Idmustint extends validate{ protected $rule = [ ' id ' = ' = ' require| Isint ' ]; protected function Isint ($value, $rule, $data, $field) { //parameters in turn are validation data, validation rules, all data (array), field names // Here we want to judge that the data requirements for validation must be positive integer if (is_numeric ($value) && is_int ($value +0) && ($value +0) > 0) { return true; } else{ //If you do not meet our criteria and return an error message, you can use the GetError () method to output the return $field in the controller . ' Not an integral type '; } }
Let's look at the corresponding operation of our controller.
Public Function Getbanner ($id) { //data to be validated $data = [ ' id ' and ' = $id, ]; Instantiation Validator $validate = new Idmustint (); If you have more validation data and more conditions and need to return all the error messages in bulk, you can add $validata->batch () $result = $validate->check ($data) before check (). if ($result) { //business logic }else{ dump ($validate->geterror ());} }
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!