Backend Development 3 min read

Implementing Data Validation with ThinkPHP5's Validate Class

This tutorial demonstrates how to create a ThinkPHP5 validation class, build a simple HTML form, and write a backend controller method to validate input data using scenes, providing step‑by‑step code examples for PHP developers.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Implementing Data Validation with ThinkPHP5's Validate Class

As a front‑end developer who often needs data validation, the author introduces ThinkPHP5's built‑in Validate object to simplify the process.

First, a custom validation class Vdate is created under app\index\validate . It defines field rules (e.g., name must be required and no longer than 10 characters, parent_id must be numeric) and a scene named save that applies these rules.

<?php namespace app\index\validate; use think\Validate; class Vdate extends Validate { protected $rule = [ ["name", "require|max:10", "不能为空|分类名不能超过10个字符"], ["parent_id", "number", "必须为数字"] ]; protected $scene = [ "save" => ["name", "parent_id"] ]; }

Next, a minimal HTML form is provided to collect the name field and submit it via GET to the controller action.

<!DOCTYPE html> <html> <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>

Finally, the backend controller method validateF retrieves the GET data, invokes the Vdate validator, checks the save scene, and handles validation errors or proceeds to insert the data, returning success or error messages accordingly.

public function validateF() { $data = input("get."); print_r($data); $validate = validate("Vdate"); if (! $validate->scene("save")->check($data)) { $this->error($validate->getError()); } $res = model("category")->add($data); if ($res) { $this->success('新增成功'); } else { $this->error("新增失败!"); } }

The article concludes that this straightforward implementation provides a functional validation workflow, and readers can refer to the official ThinkPHP documentation for more complex rule configurations.

BackendValidationPHPControllerformThinkPHP
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.