ParticleValidator是一个小巧优雅的实用的PHP验证类库,提供了一个非常简洁的API。它无需依赖其他组件,提供友好的文档,并且有利于扩展。
使用composer安装
提供非常方便的composer安装:composer require particle/validator
使用
在使用之前请确保在项目中引入了 vendor/autoload.php 文件。<?php
use ParticleValidatorValidator;
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)
Required and optional
这个方法是内置的,主要用于检测某个key的值,如果希望检测的某个值可能为空,而希望验证通过,则我们可以设置该方法的第三个参数为true。(默认值为false 代表不能为空值)。其中 required 和 optional 的区别主要是如下 required 是验证的值必须存在;而 optional 是可选的,如果key存在,则验证,不存在,则不用验证。
数组方式验证// 基本验证
$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)
alpha($allowWhitespace = false) 验证的字符包含 (a-z, A-Z),不允许空格。
between($min, $max) 验证必须在一个数值范围,如(12, 34)。
bool()布尔Boolean值验证。
callback(callable $callable) 回调验证。
creditCard() 验证信用卡,验证之前必须先安装 composer require byrokrat/checkdigit。
datetime($format = null) 验证日期。
digits() 一串数字字符串验证,不包含小数。
each(callable $callable) 遍历验证。
email() 验证邮箱。
equals($value) 验证是否相等。
float()验证浮点数。
greaterThan($value) 大于某个值。
hash($hashAlgorithm, $allowUppercase = false) md5 sha1等验证。
inArray(array $array, $strict = true) 验证是否属于数组范围内
integer($strict = false) 整数验证。
isArray() 数组验证。
json()json格式字符串验证。
length($length) 长度验证。
lengthBetween($min, $max) 长度范围验证。
lessThan($value) 小于验证。
numeric() 验证浮点数和整数。
phone($countryCode) 验证手机号,使用之前先安装 composer require giggsey/libphonenumber-for-php。
regex($regex) 正则验证。
required(callable $callback) 必须存在,不能为空。
string() 字符串验证。
url($schemes = []) 验证URL。
uuid($version = Uuid::VALID_FORMAT) 验证UUID。
提示信息覆盖
ParticleValidator为默认规则提供了默认的消息提示,当然你也可以为验证规则设置特定的消息提示以覆盖默认值。$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架构中使用验证器
很多时候,我们的项目都是进行分层开发的,例如常见的MVC,则我们可以在分层项目中调用该验证类,示例如下:use ParticleValidatorValidationResult;
use ParticleValidatorValidator;
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/.