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

How to use validator in Thinkphp5

藏色散人
藏色散人forward
2021-05-17 16:49:303211browse

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;,
    ];
}

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{         }   }

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!

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