Validator
There are many validators available via composer that can be used directly, such as:
top-think/think-validate
respect/validation
Validator top-think/think-validate
Description
Official validator for ThinkPHP
Project Address
https://github.com/top-think/think-validate
Installation
composer require topthink/think-validate
Quick Start
Create app/index/validate/User.php
<?php
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
];
protected $message = [
'name.require' => 'Name is required',
'name.max' => 'Name cannot exceed 25 characters',
'age.number' => 'Age must be a number',
'age.between' => 'Age must be between 1 and 120',
'email' => 'Invalid email format',
];
}
Usage
$data = [
'name' => 'thinkphp',
'email' => 'thinkphp@qq.com',
];
$validate = new \app\index\validate\User;
if (!$validate->check($data)) {
var_dump($validate->getError());
}
Note
TheValidate::rule()
method is not supported in webman.
Validator workerman/validation
Description
This project is the Chinese version of https://github.com/Respect/Validation
Project Address
https://github.com/walkor/validation
Installation
composer require workerman/validation
Quick Start
<?php
namespace app\controller;
use support\Request;
use Respect\Validation\Validator as v;
use support\Db;
class IndexController
{
public function index(Request $request)
{
$data = v::input($request->post(), [
'nickname' => v::length(1, 64)->setName('Nickname'),
'username' => v::alnum()->length(5, 64)->setName('Username'),
'password' => v::length(5, 64)->setName('Password')
]);
Db::table('user')->insert($data);
return json(['code' => 0, 'msg' => 'ok']);
}
}
Access via jQuery
$.ajax({
url : 'http://127.0.0.1:8787',
type : "post",
dataType:'json',
data : {nickname:'Tom', username:'tom cat', password: '123456'}
});
The result will be:
{"code":500,"msg":"Username can only contain letters (a-z) and numbers (0-9)"}
Explanation:
v::input(array $input, array $rules)
is used to validate and collect data. If data validation fails, it will throw a Respect\Validation\Exceptions\ValidationException
exception, and if validation is successful, it will return the validated data (array).
If the business code does not catch the validation exception, the webman framework will automatically catch it and return either JSON data based on the HTTP request header (similar to {"code":500, "msg":"xxx"}
) or a normal exception page. If the return format does not meet business requirements, developers can catch the ValidationException
exception themselves and return the needed data, similar to the following example:
<?php
namespace app\controller;
use support\Request;
use Respect\Validation\Validator as v;
use Respect\Validation\Exceptions\ValidationException;
class IndexController
{
public function index(Request $request)
{
try {
$data = v::input($request->post(), [
'username' => v::alnum()->length(5, 64)->setName('Username'),
'password' => v::length(5, 64)->setName('Password')
]);
} catch (ValidationException $e) {
return json(['code' => 500, 'msg' => $e->getMessage()]);
}
return json(['code' => 0, 'msg' => 'ok', 'data' => $data]);
}
}
Validator Feature Guide
use Respect\Validation\Validator as v;
// Single rule validation
$number = 123;
v::numericVal()->validate($number); // true
// Multiple rules chain validation
$usernameValidator = v::alnum()->noWhitespace()->length(1, 15);
$usernameValidator->validate('alganet'); // true
// Get the first validation failure reason
try {
$usernameValidator->setName('Username')->check('alg anet');
} catch (ValidationException $exception) {
echo $exception->getMessage(); // Username can only contain letters (a-z) and numbers (0-9)
}
// Get all validation failure reasons
try {
$usernameValidator->setName('Username')->assert('alg anet');
} catch (ValidationException $exception) {
echo $exception->getFullMessage();
// This will print
// - Username must meet the following rules
// - Username can only contain letters (a-z) and numbers (0-9)
// - Username cannot contain spaces
var_export($exception->getMessages());
// This will print
// array (
// 'alnum' => 'Username can only contain letters (a-z) and numbers (0-9)',
// 'noWhitespace' => 'Username cannot contain spaces',
// )
}
// Custom error message
try {
$usernameValidator->setName('Username')->assert('alg anet');
} catch (ValidationException $exception) {
var_export($exception->getMessages([
'alnum' => 'Username can only contain letters and numbers',
'noWhitespace' => 'Username cannot have spaces',
'length' => 'length is valid, so this message will not display'
]));
// This will print
// array(
// 'alnum' => 'Username can only contain letters and numbers',
// 'noWhitespace' => 'Username cannot have spaces'
// )
}
// Validation object
$user = new stdClass;
$user->name = 'Alexandre';
$user->birthdate = '1987-07-01';
$userValidator = v::attribute('name', v::stringType()->length(1, 32))
->attribute('birthdate', v::date()->minAge(18));
$userValidator->validate($user); // true
// Validate array
$data = [
'parentKey' => [
'field1' => 'value1',
'field2' => 'value2',
'field3' => true,
]
];
v::key(
'parentKey',
v::key('field1', v::stringType())
->key('field2', v::stringType())
->key('field3', v::boolType())
)
->assert($data); // can also use check() or validate()
// Optional validation
v::alpha()->validate(''); // false
v::alpha()->validate(null); // false
v::optional(v::alpha())->validate(''); // true
v::optional(v::alpha())->validate(null); // true
// Negation rule
v::not(v::intVal())->validate(10); // false
Differences between validate()
, check()
, and assert()
validate()
returns a boolean and does not throw an exception.
check()
throws an exception on validation failure, with the first validation failure reason obtained through $exception->getMessage()
.
assert()
throws an exception on validation failure, and all validation failure reasons can be obtained through $exception->getFullMessage()
.
Common Validation Rules List
Alnum()
only contains letters and numbers
Alpha()
only contains letters
ArrayType()
array type
Between(mixed $minimum, mixed $maximum)
validates if the input is between two other values.
BoolType()
validates if it is of boolean type
Contains(mixed $expectedValue)
validates if the input contains certain values
ContainsAny(array $needles)
validates if the input contains at least one defined value
Digit()
validates if the input only contains digits
Domain()
validates if it is a valid domain name
Email()
validates if it is a valid email address
Extension(string $extension)
validates the extension
FloatType()
validates if it is of float type
IntType()
validates if it is an integer
Ip()
validates if it is an IP address
Json()
validates if it is valid JSON data
Length(int $min, int $max)
validates if the length is within the given range
LessThan(mixed $compareTo)
validates if the length is less than the given value
Lowercase()
validates if it is lowercase letters
MacAddress()
validates if it is a MAC address
NotEmpty()
validates if it is not empty
NullType()
validates if it is null
Number()
validates if it is a number
ObjectType()
validates if it is an object
StringType()
validates if it is a string type
Url()
validates if it is a URL
For more validation rules, see https://respect-validation.readthedocs.io/en/2.0/list-of-rules/