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): ["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: 验证数据 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.
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.