Home  >  Article  >  PHP Framework  >  Let’s talk about the issue of email verification in Thinkphp5.1

Let’s talk about the issue of email verification in Thinkphp5.1

藏色散人
藏色散人forward
2021-11-16 15:07:052064browse

The followingthinkphp frameworkThe tutorial column will explain to you the issue of email verification in Thinkphp5.1. I hope it will be helpful to friends in need!

Specific question:

For example, I want to verify whether this email is legitimate. I want to use TP's own verification rules. How should I verify it? I see that the manual requires defining a User class. We define a \app\index\validate\User validator class for User verification. Is it so troublesome for the TP framework to verify email usernames? Where should this validator class be written? Is it in the same directory as the controller?

<?php
namespace app\index\controller;
use think\Controller;
use think\facade\Request;
use think\response;
use think\View;
use think\Validate;
class Register extends Controller
{
    public function regcheck(){
        $data=input(&#39;email&#39;);
        
    }
}
?>

Solution:

If you want a single verification, you can call it statically

// 验证是否有效邮箱地址
use think\facade\Validate;
Validate::isEmail(&#39;thinkphp@qq.com&#39;); // true

If there are many things to verify, it is recommended It is recommended to use a validator

The validator class can customize the directory, and it is recommended to place it in the \app\index\validate directory.

Validator class

namespace app\index\validate;
use think\Validate;
class User extends Validate
{
    protected $rule =   [
        &#39;name&#39;  => &#39;require|max:25&#39;,
        &#39;email&#39; => &#39;email&#39;,    
    ];
    
    protected $message  =   [
        &#39;name.require&#39; => &#39;名称必须&#39;,
        &#39;name.max&#39;     => &#39;名称最多不能超过25个字符&#39;,
        &#39;email&#39;        => &#39;邮箱格式错误&#39;,    
    ];
    
}

Use in the controller:

namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
    public function index()
    {
        $data = [
            &#39;name&#39;  => &#39;thinkphp&#39;,
            &#39;email&#39; => &#39;thinkphp@qq.com&#39;,
        ];
        $validate = new \app\index\validate\User;
        if (!$validate->check($data)) {
            dump($validate->getError());
        }
    }
}

The above is the detailed content of Let’s talk about the issue of email verification in Thinkphp5.1. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete