mivir / pupil
Requires
- php: >=5.3.0
This package is not auto-updated.
Last update: 2020-01-20 05:09:52 UTC
README
一个简单且强大的基于字符串的验证库。
这是 Pupil.php,该库的PHP版本。
其他可用版本
功能
- 嵌套验证规则
- 基于字符串的验证规则,适用于不同语言间的兼容性
- 通过缓存进行轻量级重新验证
变更日志
安装
通过Composer
将 "mivir/pupil": "1.*"
添加到 composer.json 的 "require" 部分。
通过下载
下载仓库。将PSR-0自动加载器指向src文件夹或手动require文件。
使用方法
基本语法如下
$pupil = new \Mivir\Pupil\Pupil(); $pupil->validate($rules, $values);
其中 $rules
和 $values
是具有匹配键的数组。规则指定为 规则字符串
;更多关于这些的信息见下文。
例如
$rules = array( 'name' => 'min(3) && max(8) && regex("^[a-zA-Z]+$")', 'country' => 'min(2)' ); $values = array( 'name' => $nameInput, 'country' => $countryInput );
两个数组不必具有相同的键,但没有匹配键的规则中的值将根本不进行评估。
validate()
方法返回一个具有以下方法的对象
isValid() // Whether the validation was successful or not hasErrors() // The opposite of isValid() errors() // Returns the fields that didn't pass validation fields() // Returns all of the fields and their validation results
规则字符串
规则字符串是Pupil指定验证规则的主要方法。
语法旨在模仿C-like语言。您可以使用逻辑运算符(&& (and)
、|| (or)
、! (not)
)、三元运算符(condition ? thenRule : elseRule
)、嵌套“块”(rule && (some || nested || rules)
)和验证函数(validationFunction("arg1", "arg2")
)。
验证函数的字符串参数,如“regex”函数中的正则表达式,应加引号。
未加引号的参数将被转换为浮点数(带小数的数字)。
对于每个验证函数,还有一个匹配的函数,以“other”开头,允许您在规则字符串指定的值之外的其他值上运行函数。这对于具有不同要求的字段很有用。例如
array( 'state' => 'otherEquals("country", "US") ? lenMin(2) : lenMin(0)' )
验证函数参数可以是字符串或数值。数值参数不应加引号或撇号:lenMin(5)
。
验证函数
以下函数是默认可用的
equals
iEquals # A case-insensitive comparison
sEquals # A strict comparison
siEquals
lenMin
lenMax
lenEquals
min
max
between
in # Compare to a list of values
required
optional
numeric
alpha
alphaNumeric
email
regex # Supply a custom regex
integer
equalsTo # Compare to another field by its key
添加自定义函数
您可以使用以下语法添加自己的验证函数
$pupil->addFunction($name, $callable);
其中 callable 是匿名函数或使用 create_function 创建的函数,至少应接受两个参数: $allValues
和 $value
。 $allValues
是一个包含当前正在验证的每个值的对象,而 $value
包含我们正在验证的值。可以在规则字符串中像这样传递更多参数
customFunction("arg1", "arg2")
函数名不区分大小写。