Home > PHP Framework > ThinkPHP > How to use validator in Thinkphp5

How to use validator in Thinkphp5

藏色散人
Release: 2021-05-18 09:02:15
forward
3250 people have browsed it

The following is an introduction to the validator in Thinkphp5 from the thinkphp tutorial column. I hope it will be helpful to friends in need!

The method of using the validator is relatively simple. The main thing is that we need to define the validation rules first. Thinkphp5 stipulates that if we want to use the validator, we need to create the file in the validate folder.

This folder is at the same level as controller and model

We will define the validator under this folder and encapsulate it into a separate class so that it can be used anywhere in the future.

<?php
namespace app\admin\validate;

use think\Validate;

class Add extends Validate{
    protected $rule = [
        &#39;name&#39;  =>  &#39;require&#39;,   
        &#39;phone&#39;=>&#39;require|max:11|min:11|regex:/^1[3-8]{1}[0-9]{9}$/&#39;    
    ];
    protected $message = [
        &#39;name.require&#39;=>&#39;用户名必须填写&#39;,
        &#39;phone.require&#39;=>&#39;请输入手机号码&#39;,
        &#39;phone.max&#39;=>&#39;手机号码最多不能超过11位&#39;,
        &#39;phone.min&#39;=>&#39;手机号码不能少于11位&#39;,
        &#39;phone.regex&#39;=>&#39;手机号码格式不正确&#39;,
    ];
}
Copy after login

We will call this class in the controller to verify the value received in the controller

public function insertUser(Request $request)
    {
        $msg = [
            "status" => null,
            &#39;msg&#39; => null
        ];
        $name = $request->param(&#39;name&#39;);
        $phone = $request->param(&#39;phone&#39;);
        $data = [
            &#39;name&#39; => $name,
            &#39;phone&#39; => $phone
        ];
        $addval = new AppAdd();
        if (!$addval->check($data)) {
            $msg[&#39;status&#39;] = 0;
            $msg[&#39;msg&#39;] = $addval->getError();
        } else{         }   }
Copy after login

Use the method to get the instance of the class through new, and then call the check method in this object Validate data

Related recommendations:The latest 10 thinkphp video tutorials

The above is the detailed content of How to use validator in Thinkphp5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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