renanhangai / validator
使用非常简单的语法验证任何PHP变量。
Requires
- marcj/topsort: ^1.1
Requires (Dev)
- phpunit/phpunit: ^6.4
- rtlopez/decimal: ^1.0
Suggests
- rtlopez/decimal: Allows decimal validation using v::decimal($digits, $decimal)
README
使用易于定义的规则验证对象(见API参考)
安装
composer require renanhangai/validator
入门
简单地验证一些数据
use libweb\Validator as v; // Data to be validated $data = array( "name" => "John Doe", "age" => "45", ); // Validate the data against the rule $data = v::validate( $data, array( "name" => v::s(), //< String validator "age" => v::i(), //< Integer validator "address?" => v::s(), //< Optional string validator )); $data->name === "John Doe"; $data->age === 45; $data->address === null;
另一个示例
简单地验证一些数据
use libweb\Validator as v; $data = array( "name" => "John Doe", "age" => "45", "password" => "123456", "children" => array( array( "name" => "John Doe Jr", "age" => 15 ), array( "name" => "Mary Doe", "age" => 17 ), ), ); $data = v::validate( $data, array( "name" => v::s(), //< String validator "age" => v::i(), //< Integer validator "password" => v::s()->minlen( 6 ), "children" => v::arrayOf(array( "name" => v::s(), "age" => v::i(), )), ));
链式操作
每个方法都可以通过使用 ->
来链式调用
v::s()->str_replace( "foo", "bar" )->regex('/testbar$/')->minlen(10) // Will pass on "mytestfoo", "another_testfoo", "testbar", "mytestbar"
API参考
摘要
- 类型验证器
any()
arrayOf($rule)
boolval()
b()
date($format = null, $out = null)
decimal($digits, $decimal, $decimalSeparator = null, $thousandsSeparator = null)
floatval($decimal = null, $thousands = null, $asString = false)
f($decimal = null, $thousands = null, $asString = false)
instanceOf($type)
intval()
i()
obj($definition)
strval($trim = true)
s($trim = true)
- 字符串规则
- 混合
- 地区规则
- 元数据
- 必填性
- 数字规则
方法
-
验证所有对象
-
验证数组中的每个元素是否符合$rule规则
-
从字符串中移除$chars中找到的任何字符
-
将值转换为布尔值
-
调用函数$fn来验证值
-
巴西CNPJ验证器
-
巴西CPF验证器
-
date($format = null, $out = null)
使用格式将值转换为日期(如果已经是\DateTime则保持不变)
-
decimal($digits, $decimal, $decimalSeparator = null, $thousandsSeparator = null)
将值转换为具有$digits和$decimal的十进制数(需要rtlopes\Decimal)
-
添加规则依赖项。 (仅适用于对象)
-
floatval($decimal = null, $thousands = null, $asString = false)
将值转换为浮点数
-
检查对象是否为给定类型的实例
-
将值转换为整数,如果无法安全转换则失败
-
检查字符串或数组长度
-
将值映射到另一个值
-
检查字符串长度是否至少为$min
-
将值转换为对象并验证其字段
-
可选验证器(如果为null或''则绕过)
-
preg_replace($search, $replace)
使用$replace替换字符串上的$search模式(回调或字符串)
-
范围验证器
-
根据$pattern验证值
-
必填验证器(如果为null或''则失败)
-
检查值是否在集合中
-
可跳过的验证器(如果为null或''则跳过,且不设置属性)
-
str_replace($search, $replace)
替换字符串上的字符
-
将对象转换为字符串值
-
从字符串中删除任何不在$chars中找到的字符