求推荐适用于PHP的简易表单验证库
Hey there! For a simple, no-fuss PHP validation library that lets you pass rules and field names easily, plus grab error messages without jumping through hoops, Respect/Validation is my top recommendation. It’s lightweight, flexible, and feels really intuitive to work with—perfect for quick validation needs.
First, install it via Composer (the easiest way):
composer require respect/validation
Basic Usage Example
Let’s say you need to validate a user registration form. You can define rules tied directly to your field names, then run the validation and pull errors in one go:
use Respect\Validation\Validator as v; // Your input data (e.g., from $_POST) $input = [ 'username' => 'johndoe123', 'email' => 'invalid-email', 'age' => 17 ]; // Define validation rules, with clear field names $validator = v::key('username', v::notEmpty()->alpha()->setName('Username')) ->key('email', v::notEmpty()->email()->setName('Email Address')) ->key('age', v::numericVal()->min(18)->setName('Age')); try { // Run the validation $validator->assert($input); echo "All fields are valid!"; } catch (\Respect\Validation\Exceptions\ValidationException $e) { // Get a clean array of error messages $errors = $e->getMessages(); foreach ($errors as $field => $message) { echo "- $message<br>"; } }
This will output:
- Username must contain only letters
- Email Address must be a valid email
- Age must be greater than or equal to 18
You can even customize error messages per rule if you want more control:
$emailRule = v::email()->setName('Email')->setMessage('{{name}} needs to be a real email—no fake stuff!');
If you don’t want to use Composer or need something even more minimal, Valitron is a great choice. It’s a standalone library that works with arrays, and error messages are straightforward to access.
Here’s a quick example:
require 'Valitron/Validator.php'; $v = new Valitron\Validator($input); $v->rule('required', ['username', 'email']); $v->rule('email', 'email'); $v->rule('min', 'age', 18); // Set custom field names for error messages $v->labels([ 'username' => 'Username', 'email' => 'Email Address', 'age' => 'Age' ]); if (!$v->validate()) { // Get error messages grouped by field $errors = $v->errors(); // Or get a flat list of messages $flatErrors = $v->errors(true); }
Both libraries let you pass rules and field names easily, and error retrieval is simple—no complicated setup required. Pick Respect if you want more flexibility and rule options, or Valitron if you need something dead-simple and dependency-free.
内容的提问来源于stack exchange,提问作者user11322597

