ThinkPHP 6.0 learning notes - verifier

Keywords: PHP Attribute less JSON

Validator

By:Mirror Wang Yuyang

Verifier definition

For the use of verifier, it must be defined; the system provides a command to directly produce a verifier class:

php think make:validate User

Generate a validate folder under the automatic re application directory and generate the User.php class

namespace app\validate;
use think\Validate;
class User extends Validate
{
    /**
     * Define validation rules
     * Format: 'field name' = > ['rule 1', 'rule 2'...]
     *      'Field name '= >' rule 1| rule 2... '
     *
     * @var array
     */	
	protected $rule = [
        'name'      =>      'require|max:20',
        'price'     =>      'number|between:1,100',
        'email'     =>      'email'
    ];
    
    /**
     * Define error messages
     * Format: 'field name. Rule name' = > 'error information'
     *
     * @var array
     */	
    protected $message = [
        'name.require'      =>  'Name cannot be empty',
        'name.max'          =>  'No more than 20 names',
        'price.number'      =>  'Price must be a number',
        'price.between'     =>  'Price at 1~100 Between',
        'email'             =>  'Mailbox format error'
    ];
}

Two automatically generated properties:

$rule: define rules

$message: define the error message. If you do not define the default error message of the error message prompt

After the verifier is defined, call the test to create a Verify.php controller:

namespace app\controller;
use app\validate\User;
use think\exception\ValidateException;

class Verify
{
    public function index()
    {
        try {
            validate(User::class)->check([
                'name'  =>  'Crayon Shin Chan',
                'price' =>   90,
                'email' =>  'xiaoxin@qq.com'
            ]);
        } catch (ValidateException $err){
            dump($err->getError());
        }
    }
}

When there is an error in the validation rule, the field judgment will be stopped

Batch verification

class Verify
{
    public function index()
    {
        try {
            $result = validate(User::class)
                ->batch(true)->check([
                'name'  =>  'Crayon Shin Chan',
                'price' =>   90,
                'email' =>  'xiaoxin@qq.com'
            ]);
            if(true !== $result){
                dump($result);
            }
        } catch (ValidateException $err){
            dump($err->getError());
        }
    }
}

Custom rules

Some commonly used rules are provided in the system; at the same time, developers can customize the rules:

protected function checkName($value,$rule)
{
    return $rule != $value ? true : 'Illegal characters present';
}

The custom rule supports five parameters:

  • Validation data
  • Validation rules
  • All data (array)
  • Field name
  • Field description

Validation rules

Rule definition

protected $rule = [
        'name'      =>      'require|max:20',
        'price'     =>      'number|between:1,100',
        'email'     =>      'email'
    ];

Support not only string mode, but also array mode

protected $rule = [
        'name'      =>      [
						'require',
						'max' =>	10
         ],
        'price'     =>      [
        				'number',
            			'between' => '1,100'
        ],
        'email'     =>      ['email']
    ];

Array mode is used when the rules are complex

Independent verification:

All the above validation rules need to call the validator file in the validate directory, while Think supports independent validation under the controller file. This independent and unique way of calling the validator file is independent and unique

namespace app\controller;
use think\facade\Validate;
class Verify
{
    public function index()
    {
        $validate = Validate::rule([
            'name'      =>      'require|max:20',
            'price'     =>      'number|between:1,100',
            'email'     =>      'email'
        ]);
        $result = $validate->chech([
            'name'  =>  'Crayon Shin Chan',
            'price' =>   90,
            'email' =>  'xiaoxin@qq.com'
        ]);
        if (!$result){
            dump($validate->getError());
        }
    }
}

Independent validation supports the definition of objectification, but does not support the definition of attribute methods:

namespace app\controller;
use think\facade\Validate;
use think\facade\ValidateRule as Rule;
class Verify
{
 public function index()
 {
     $validate = Validate::rule([
         'name'      =>      'Rule::isRequire()->max(20)',
         'price'     =>      'Rule::isNumber()->between([1,100])',
         'email'     =>      'Rule::isEmail()'
     ]);
     $result = $validate->chech([
         'name'  =>  'Crayon Shin Chan',
         'price' =>   90,
         'email' =>  'xiaoxin@qq.com'
     ]);
     if (!$result){
         dump($validate->getError());
     }
 }
}

Independent validation supports closure custom methods: (multiple field rules are not supported)

$validate = Validate::rule([
	'name'=> function($value){
                return $value != '' ? true : 'Name cannot be empty';
	},
	'price'=> function($value){
	    return $value > 0 ? true:'Not less than zero';
	}
]);

error message

Define prompt information separately

Define the message property in the validator class:

protected $message = [
    'name.require'      =>  'Name cannot be empty',
    'name.max'          =>  'No more than 20 names',
    'price.number'      =>  'Price must be a number',
    'price.between'     =>  'Price at 1~100 Between',
    'email'             =>  'Mailbox format error'
];

The error information supports array definition and is delivered to the front end through JSON

protected $message = [
	'name.require' => ['code' => 1001, 'msg' => 'Name must'],
	'name.max'     => ['code' => 1002, 'msg' => 'The name cannot exceed 25 characters at most'],
	'age.number'   => ['code' => 1003, 'msg' => 'Age must be a number'],
	'age.between'  => ['code' => 1004, 'msg' => 'Age must be 1~120 Between'],
	'email'        => ['code' => 1005, 'msg' =>'Mailbox format error'],
];

Independent validation definition error prompt

ValidateRule::isEmail(null,'Incorrect format')

Parameter 1: validation rules

Parameter 2: user defined error prompt

You can also use the message() method independently:

Validate->[......]->message([......])

Verification scenario

Verification scenario settings: that is, whether a specific scenario is written for verification, independent verification does not exist;

New data needs to verify mailbox information, while modified data does not need to verify mailbox information

namespace app\validate;
use think\Validate;

class User extends Validate
{
	protected $rule = [
        'name'      =>      'require|max:20',
        'price'     =>      'number|between:1,100',
        'email'     =>      'email'
    ];

    protected $message = [
        'name.require'      =>  'Name cannot be empty',
        'name.max'          =>  'No more than 20 names',
        'price.number'      =>  'Price must be a number',
        'price.between'     =>  'Price at 1~100 Between',
        'email'             =>  'Mailbox format error'
    ];

    protected $scene = [
        // Three new data validation fields
        'insert'       =>   ['name','price','email'],
        // Update data validation two fields
        'edit'         =>   ['name','price']
    ];
}
try {
    validate(User::class)->scene('edit')->check([
        'name'  =>  'Crayon Shin Chan',
        'price' =>   90,
        'email' =>  'xiaoxinqq.com'
    ]);
} catch (ValidateException $err){
    dump($err->getError());
}

Setting scene() on the control side limits the success of only verifying the name and price fields

Scene supports to define a method for a single scene. The naming standard of the method is scene + scene name, which is written by hump;

At the same time, public methods are supported in the validation class to define the details in the scene:

public function sceneEdit()
{
    return $this->only(['name','price'])
        ->append('name','min:5')
        ->remove('price','between')
        ->append('price','require|max:20');
}

append

Remove remove

(do not operate on a field multiple times, which will result in overwriting; you can operate at the same time)

only constraint field

Route validation

Route validation: call the validation class in route parameters for validation

protected $rule = [
    'id' => 'number|between:1,10'
];
protected $message = [
    'id.between'	=>	'id Between 1~10 Between',
    'id.number'		=>	'id Must be a number'
];
protected $scene = [
    'route'	=>	['id'];
];
Route::rule('vr/:id','Verify/route')->validate(User::class,'route');//Execute route scenario only

It also supports the use of independent verification methods, which will not be discussed here

Built in rules

<ThinkPHP6.0 Development Manual - built in rules>

Static methods support two forms: number(), isNumber() method validation

Format validation class

Properties / methods describe
require/::isRequire Cannot be empty
number/::isNumber Verify that the field is a pure number
integer/::isInteger Verify that the field is an integer
float/::isFloat Verify that the field is a floating point number
boolean/::isBoolean Verify that the field is Boolean
email/::isEmail Verify that the field is in mailbox format
array/isArray Verify that the field is an array
accepted/isAccepted Verify that the field is yes/on
date/isDate Verify that the field is a valid date
alpha/isAlpha Verify that the field is alphabetic
alphaNum/isAlphaNum Verify that the fields are alphanumeric
alphaDash/isAlphaDash Verify that the fields are alphanumeric underlined and dashed
chs/isChs Verify whether the field is a Chinese character
chsAlpha/isChsAlpha Verify whether the field is a Chinese character letter
chsAlphaNum/isChsAlphaNum Verify that the fields are Chinese letters and numbers
chsDash/isChsDash Verify that the fields are alphanumeric underscores, dashes, and Chinese characters
cntrl/isCntrl Verify that the field is a control character (space, indent)
graph/isGraph Verify that the field is a printable character (excluding spaces)
print/isPrint Verify that the field is printable (including spaces)
lower/isLower Verify that the field is lowercase
upper/isUpper Verify that the field is capitalized
space/isSpace Verify that the field is blank
xdigit/isXdigit Verify that the field is hexadecimal
activeUrl/isActiveUrl Verify that the field is a valid domain name
url/isUrl Verify that the field is a valid URL address
ip/isIp Verify that the field is a valid IP address
deteFormat:format Date time format of validation field
mobile Verify that the field is a valid phone number
idCard Authentication ID format
macAddr Verify MAC address format
zip Verify valid zip code

Length and interval verification class

attribute describe
in Verify that the field is in a range
notIn Verify that the field is no longer in a range
between Verify that the field is in a range
notBetween Verify that the field is not in an interval
length Verify that the length is in a range or a specified length
max/min Verify maximum / minimum length (size)
after Verify after a date
before Verify before a date
expire Verify that the current value is within a certain time interval
allowip Verify that the current value is within an IP segment
denyIp Verify that the current value IP is a no access IP

Field comparison class

attribute describe
confirm:field Verify that the value of the field is consistent with other values
different:field Verify that the value of the field is not consistent with other values
eq/same/= Verify that is equal to a value
egt / >= Verify that a value is greater than or equal to
gt/> Verify that is greater than a value
elt/<= Verify that a value is less than or equal to
lt/< Verify that it is less than a value

Upload verification class

attribute describe
file Verify whether the uploaded file is a file
image Verify whether it is an image file (width height type can be constrained)
fileExt Verify file suffix (suffix list can be allowed)
fileMime Verify file types (file types can be allowed)
fileSize Verify file size (bytes size that can be allowed)

Other validation classes

filter validation:

Support the use of filter VaR for validation, such as:

'ip'=>'filter:validate_ip'

Regular validation: regex

Support regular expression validation:

'data' => '\d{6}';
'data' => 'regex:\d{6}';

If the expression contains or logic, it needs to be defined in array mode

'data' => ['regex'=>'/^(yes|on|1)$/i']

It can also be predefined

namespace app\index\validate;
use think\Validate;
class User extends Validate
{
    protected $regex = [ 'zip' => '\d{6}'];
    
    protected $rule = [
        'name'  =>  'require|max:25',
        'email' =>  'email',
    ];
}

Then you can use

'zip'	=>	'regex:zip',

Form token validation: Token

Reference connection: https://www.kancloud.cn/manual/thinkphp6_0/1037632

Validation request field unique: unique

You can verify that the current requested field value is unique

unique:[table],[field],[except],[pk]

Table: specify data table

field: other fields

except: exclude a primary key value

pk: specify a primary key value exclusion

// Indicates whether the value of the verify name field is unique in the user table (without prefix)
'name'   => 'unique:user',
// Verify other fields
'name'   => 'unique:user,account',
// Exclude a primary key value
'name'   => 'unique:user,account,10',
// Specify a primary key value exclusion
'name'   => 'unique:user,account,10,user_id',

require:

attribute describe
requireIf:field,value When verifying that the value of a field is equal to a value, you must
requireWith:field When verifying that a field has a value, you must
requireWithout:field When verifying that a field has no value, you must
requireCallback:callable Verify that the field must be

Static call validation

Static call: use facade mode for call verification, suitable for verifying single data

There may be conflicts when introducing Validate in the facade, which should be noted;

dump(Validate::isEmail('xiaoxin@qq.com'));

Static call supports multi rule validation: checkRule()

Validate::checkRule(10, 'number|between:1,10');

Annotation verification

Reference official: https://www.kancloud.cn/manual/thinkphp6_0/1375936

Install additional extensions:

composer require topthink/think-annotation

Posted by e_00_3 on Tue, 21 Apr 2020 01:47:52 -0700