Home > PHP Framework > ThinkPHP > body text

How to use validators in ThinkPHP6

王林
Release: 2023-06-21 09:45:18
Original
3134 people have browsed it

With the continuous development of the Internet, more and more people are beginning to use PHP for website development. In PHP, using frameworks can greatly improve development efficiency, and ThinkPHP is a very popular framework. In ThinkPHP, the validator is a very important component that can help us verify the data submitted by users to ensure the correctness of the data. So this article will introduce how to use validators in ThinkPHP6.

1. What is a validator

A validator is a tool used to verify data. It can verify the format, length, legality, etc. of the data submitted by the user to ensure that the data correctness. In ThinkPHP6, the validator is an independent component and you can implement a custom validator by inheriting the Validation class.

2. Basic usage of validator

In ThinkPHP6, the use of validator is very simple. First, we need to define a validator class to specify the fields that need to be validated and the corresponding validation rules. The following is an example:

<?php

namespace appindexalidate;

use thinkValidate;

class User extends Validate
{
    protected $rule = [
        'name'  =>  'require|max:25',
        'email' =>  'email',
    ];

    protected $message = [
        'name.require'  =>  '名称不能为空',
        'name.max'      =>  '名称最多不能超过25个字符',
        'email'         =>  '邮箱格式错误',
    ];
}
Copy after login

In the above code, we first define a validator class named User, specifying the fields that need to be validated and the corresponding validation rules. For example, the name field needs to meet the rules of being non-empty and up to 25 characters, and the email field needs to meet the rules of email format. At the same time, we also define a $message array to store the error message of each verification rule.

After defining the validator class, we can use this validator in the controller to verify data. The following is an example:

<?php

namespace appindexcontroller;

use thinkController;
use appindexalidateUser;

class Index extends Controller
{
    public function index()
    {
        $data = [
            'name'  =>  'Tom',
            'email' =>  'test@example.com',
        ];

        $validate = new User();

        if (!$validate->check($data)) {
            dump($validate->getError());
            // 验证失败
        }
        else {
            // 验证成功
        }
    }
}
Copy after login

In the above code, we first define a $data array to store the data that needs to be verified. Then, we instantiate a User validator object and use the check method to verify the $data array. If the verification fails, you can use the getError method to obtain the error message. If the verification is successful, you can continue with other operations.

3. Advanced usage of validators

In addition to basic validation rules, ThinkPHP6 also provides many advanced validator functions to meet more complex validation needs.

  1. Scenario verification

Sometimes, the fields that need to be verified for different operations may be different. At this time, we can use scenario verification to solve this problem. In ThinkPHP6, we can define different scenarios in the validator class and specify the current scenario that needs to be used in the controller. Here is an example:

<?php

namespace appindexalidate;

use thinkValidate;

class User extends Validate
{
    protected $rule = [
        'name'  =>  'require|max:25',
        'email' =>  'email',
    ];

    protected $message = [
        'name.require'  =>  '名称不能为空',
        'name.max'      =>  '名称最多不能超过25个字符',
        'email'         =>  '邮箱格式错误',
    ];

    protected $scene = [
        'add'   =>  ['name', 'email'],
        'edit'  =>  ['name'],
    ];
}
Copy after login

In the above code, we define two scenarios, namely add and edit. Among them, the add scenario requires verification of the name and email fields, while the edit scenario only requires verification of the name field. In this way, when used in the controller, you can specify the current scene that needs to be used.

$data = input('post.');
$validate = new User();
if (!$validate->scene('add')->check($data)) {
    // 验证失败
}
else {
    // 验证成功
}
Copy after login
  1. Custom validation rules

In addition to the built-in validation rules, we can also customize validation rules to meet specific needs. In ThinkPHP6, we can add custom validation rules through the addRule method. Here is an example:

<?php

namespace appindexalidate;

use thinkValidate;

class User extends Validate
{
    protected $rule = [
        'email' =>  'email|checkEmail',
    ];

    protected $message = [
        'email.email'  =>  '邮箱格式错误',
        'email.checkEmail'  =>  '邮箱不允许注册',
    ];

    protected function checkEmail($value, $rule, $data)
    {
        if (in_array($value, ['admin@example.com', 'superadmin@example.com'])) {
            return false;
        }
        else {
            return true;
        }
    }
}
Copy after login

In the above code, we first add a checkEmail rule to the validation rules of the $email field. Then, the error message of the checkEmail rule is defined in the $message array. Finally, a checkEmail method is defined in the validate class to implement our custom verification logic (in this example, the two email addresses admin@example.com and superadmin@example.com are not allowed). In this way, when performing data verification, the checkEmail method will be automatically called for verification.

The above are the basic methods and advanced usage of validators in ThinkPHP6. The validator is a very important component that can ensure the correctness of our data and also improve the readability and maintainability of the code. In actual development, we should use the validator flexibly according to the actual situation to help our development work.

The above is the detailed content of How to use validators in ThinkPHP6. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!