实用的PHP验证器类Validator 2018年03月17日 22:05helloweba.net 作者:月光光 标签:PHP Laravel Particle\Validator是一个小巧优雅的实用的PHP验证类库,提供了一个非常简洁的API。它无需依赖其他组件,提供友好的文档,并且有利于扩展。
使用composer安装 提供非常方便的composer安装: composer require particle/validator 使用
在使用之前请确保在项目中引入了 vendor/autoload.php 文件。
<?php
use Particle\Validator\Validator;
require './vendor/autoload.php';
$v = new Validator;
$v->required('first_name')->lengthBetween(2, 30)->alpha();
$v->required('last_name')->lengthBetween(2, 40)->alpha();
$data = [
'first_name' => 'John',
'last_name' => 'Doe',
];
$result = $v->validate($data);
$result->isValid(); // 返回bool(true or false)
// 基本验证
$values = [
'user' => [
'username' => 'bob',
]
];
$v = new Validator;
$v->required('user.username')->alpha();
$result = $v->validate($values);
$result->getValues() === $values; // bool(true)
内置验证规则 allowEmpty(callable $callback)是否可以为空值,true则通过 反之亦然。
$v = new Validator;
// 如果用户名存在,则验证通过
$v->required('name')->allowEmpty(function (array $values) {
return $values['namePresent'] === true;
});
$v->validate(['namePresent' => true, 'name' => 'John'])->isValid(); // true
$v->validate(['namePresent' => true])->isValid(); // true
$v->validate(['namePresent' => false])->isValid(); // false
alnum($allowWhitespace = false) 包含数字和字母,不允许空格,(a-z, A-Z, 0-9) $v = new Validator;
$v->required('first_name')->lengthBetween(0, 5);
$v->required('last_name')->lengthBetween(0, 5);
$v->overwriteDefaultMessages([
LengthBetween::TOO_LONG => 'It\'s too long, that value'
]);
$v->overwriteMessages([
'first_name' => [
LengthBetween::TOO_LONG => 'First name is too long, mate'
]
]);
$result = $v->validate([
'first_name' => 'this is too long',
'last_name' => 'this is also too long',
]);
var_dump($result->getMessages());
$v = new Validator;
// 定义一个插入时候的验证规则
$v->context('insert', function(Validator $context) {
$context->required('first_name')->lengthBetween(2, 30);
});
// 定义一个更新时候的验证规则
$v->context('update', function(Validator $context) {
$context->optional('first_name')->lengthBetween(2, 30);
});
$v->validate([], 'update')->isValid(); // bool(true)
$v->validate([], 'insert')->isValid(); // bool(false), because first_name is required.
在MVC架构中使用验证器 use Particle\Validator\ValidationResult;
use Particle\Validator\Validator;
class MyEntity
{
protected $id;
public function setId($id)
{
$this->id = $id;
return $this;
}
public function validate() {
$v = new Validator;
$v->required('id')->integer();
return new $v->validate($this->values());
}
protected function values()
{
return [
'id' => $this->id,
];
}
}
// in a controller:
$entity = new Entity();
$entity->setId($this->getParam('id'));
$result = $entity->validate();
if (!$result->isValid()) {
return $this->renderTemplate([
'messages' => $result->getMessages() // or maybe even just pass in $result.
]);
}
当然,如果默认的验证规则不能满足时,我们可以再扩展定制规则,有关定制扩展规则,请参考项目官网:http://validator.particle-php.com/en/latest/.