Implementing Validation in ThinkPHP5 Using the Built-in Validate Class
This article demonstrates how to use ThinkPHP5's built‑in Validate class to define validation rules and scenes, create a simple HTML form for data submission, and process the input in a backend controller, providing complete code examples for each step.
This guide explains how to implement data validation in a ThinkPHP5 application by leveraging the framework's built‑in Validate class. It covers creating a custom validator, building a minimal HTML form for user input, and handling the validation logic in a controller method.
Validator definition (PHP):
<?php
namespace app\index\validate;
use think\Validate;
class Vdate extends Validate{
// Each field corresponds to a rule (first layer)
protected $rule = [
["name","require|max:10","不能为空|分类名不能超过10个字符"],
["parent_id","number","必须为数字"],
];
// Validation scenes (second layer)
protected $scene = [
"save" => ["name","parent_id"],
];
}The validator can be placed in the app\index\validate directory or under common as long as the namespace is correct.
Frontend HTML form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>验证数据</title>
</head>
<body>
<form action="{:url('index/validateF')}" method="GET">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
</body>
</html>This simple form sends a GET request with a name parameter to the validateF action of the Index controller.
Backend controller method handling validation:
public function validateF() {
$data = input("get.");
print_r($data);
$validate = validate("Vdate"); // use the validator
if(!$validate->scene("save")->check($data)){
$this->error($validate->getError()); // built‑in error response
}
// Continue with business logic
$res = model("category")->add($data);
if($res){
$this->success('新增成功');
}else{
$this->error("新增失败!");
}
}When the request passes validation, the data is saved via the category model; otherwise, an error message is returned.
Following these steps provides a complete, functional validation workflow in ThinkPHP5.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
