Method of Thinkphp5 Framework Using validate to Realize Verification Function

  • 2021-12-19 06:18:57
  • OfStack

This article illustrates how the Thinkphp5 framework uses validate to implement the verification function. Share it for your reference, as follows:

As the front-end er, I have a personal experience in verifying this piece. Although I am gradually handy, I never have a built-in function to use. tp5 provides exactly one. This article briefly introduces and implements the following. Mainly to achieve 1.

The implementation of validation is based on the built-in object validate of tp5.

Under Index modularization, index controller peer directory creates an validate file, which contains an Vdate. php verification file. This file can also be placed under common directory, as long as namespace is correct. The code is as follows


<?php
  namespace app\index\validate;
  use think\Validate;
  class Vdate extends Validate{
   // Each field corresponds to 1 Rule, this is the first 1 Layer 
    protected $rule=[
     ["name","require|max:10"," Cannot be empty | Category name cannot exceed 10 Characters "],
     ["parent_id","number"," Must be a number "],
    /* ["id","number"," Must be a number "],
     ["status","number|in:1,0,-1"," Must be a number | It must be yes 0,-1,1"],*/
    ];
   // Application scenario, which is the first 2 Layer 
    protected $scene=[
     "save"=>["name","parent_id"],
    ];
  }

You can write multiple fields, as I commented.

Then the front-end page code


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title> Validation data </title>
</head>
<body>
  <form action="{:url('index/validateF')}" method="GET">
    <input type="text" name="name">
    <input type="submit" value=" Submit ">
  </form>
</body>
</html>

The corresponding validateF under the back-end controller index


public function validateF()
{
    $data=input("get.");
    print_r($data);
    $validate=validate("Vdate"); // Use authentication 
    //scene("save")->check($data) Built-in method 
    if(!$validate->scene("save")->check($data)){
      $this->error($validate->getError());// Built-in error return 
    }
    // Remaining operations 
    $res=model("category")->add($data);
    if($res){
     $this->success(' New Success ');
    }else{
     $this->error(" Add failed! ");
    }
}

That's it. Very simple implementation. About the rules of each field, there are many contents that can be referred to in manuals or official Internet cafes.

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: