psecio/validation

一个简单的验证库

0.5.5 2018-08-18 13:31 UTC

This package is auto-updated.

Last update: 2024-09-15 10:55:59 UTC


README

该库旨在成为一个基于规则的简单且可重用的输入验证库。

示例

<?php

$v = \Psecio\Validate\Validator::getInstance();

$data = [
    'foo' => 'bar'
];
$rules = [
    'foo' => 'required|alpha'
];

$result = $v->execute($rules, $data);
var_export($result);

?>

消息

您还可以使用 execute 方法的第三个参数 $messages 定义自定义失败消息。数组中的键名与值名 + 检查类型相匹配。例如

<?php
$v = \Psecio\Validate\Validator::getInstance();
$data = [
    'foo' => 'bar'
];
$rules = [
    'foo' => 'required|alpha'
];
$messages = [
	'foo' => ['alpha' => 'This is a custom message']
];

$result = $v->execute($rules, $data, $messages);
var_export($result);

在上面的示例中,我们为 foo 值上的 alpha 检查定义了自定义消息。如果该检查失败,错误消息输出将使用新的自定义消息而不是默认消息。

获取错误

execute 方法的返回值为 false 时,有两种方法可以获取错误

  • errors 方法将返回一组嵌套的键/值失败消息集合(顶层是值名,每个检查失败消息都在其下方)
  • errorArray 方法将返回一个扁平化的消息集合,这对于输出到页面非常有用,无需进行太多的循环

检查

以下是 Validation 支持的检查类型列表

alpha

仅检查字母字符

alphanum

仅检查字母数字字符

numeric

确保提供的值是数字(整数、浮点数等)

integer

仅检查整数值。也可以包括最小值和最大值

// Minimum of 1, max of 10
$rules = ['mynumber' => 'integer[1,10]'];

boolean

检查布尔值(truefalse01 以及字符串 '0''1'

array

确保提供的值是数组

length

确保(字符串)长度与要求匹配。您必须提供最小值,但也可以定义最大值

// Using just the minimum, checking for a length of at least 3
$rules = ['mystring' => 'length[3]']

// Using both minimum and maximum, check for a length between 3 and 10
$rules = ['mystring' => 'length[3,10]']

date

确保提供的值是日期(由 strtotime 解析)

before

检查值(可解析的日期)是否在提供的日期之前(由 strtotime 解析)

// Check to see if the date provided is before yesterday
$rules = [
    'myinputdate' => 'before[yesterday]'
];

after

检查值(可解析的日期)是否在提供的日期之后(由 strtotime 解析)

// Check to see if the date is in the last three days
$rules = [
    'myinputdate' => 'after[-3 days]'
];

in

确保提供的值在值集中

// Check to see if the value is one of "foo", "bar" or "baz"
$rules = [
    'myvalue' => 'in[foo,bar,baz]'
]

json

确保值是有效的 JSON 格式化字符串(使用 json_decode

required

确保值存在

ip

确保提供的值是有效的 IPv4 或 IPv6 格式地址

email

确保提供的值是有效的电子邮件地址格式

regex

确保值至少匹配一次指定的正则表达式

$rules = [
    'mystring' => 'regex[/[0-9a-z]+/]'
]

equals

此检查可用于检查两个字段的值是否完全匹配。

$data = [
    'foo' => 'test1',
    'bar' => 'test1'
];
$rules = [
    'bar' => 'equals[foo]'
];

callback

此检查可用于通过静态类方法调用自定义逻辑。例如,如果您的类是

<?php
class Foo {
	public static function check($input) { ... }
}
?>

那么您的规则将类似于以下内容

$rules = [
	'mystring' => 'callback[Foo::check]'
];

然后 check 方法应返回一个布尔结果。