phputil/validator

PHP的简单而强大的验证器

2.5.2 2016-08-18 21:11 UTC

This package is auto-updated.

Last update: 2024-09-23 03:50:21 UTC


README

PHP的简单而强大的验证库。

Build Status

我们使用语义版本控制。请参阅我们的发布版本

安装

composer require phputil/validator

仅依赖于phputil/rtti

示例

一个逐步示例,用于展示其用法。

// Suppose that your application receives an object in a JSON like this:
$json = <<<EXAMPLE
{
	"name": "Bob Developer",
	"likes": 150,
	"phone": { "number": "99988-7766", "notes": "WhatsApp, Telegram" },
	"friends": [ "Suzan", "Mike", "Jane" ]
}
EXAMPLE;
// So you transform the JSON into an object
$obj = json_decode( $json );
// Now you want to validate this object, and you create a Validator
$validator = new Validator();
// And define the rules
$rules = array(
	// name must have from 2 to 60 characters
	'name' => array( Rule::LENGTH_RANGE => array( 2, 60 ), Option::LABEL => 'Name' ),
	// likes must be greater or equal to zero
	'likes' => array( Rule::MIN_VAUE => 0 ),
	// for the phone...
	'phone' => array( Rule::WITH => array(
		// number must follow a regex
		'number' => array(
			Rule::REGEX => '/^[0-9]{5}\\-[0-9]{4}$/',
			Option::LABEL => 'Phone Number'
			)
	) ),
	// have a friend limit
	'friends' => array( Rule::MAX_COUNT => 100 )
);
// And define the messages (we also could load it from a JSON file)
$messages = array(
	'en' => array( // "en" means "english" locale. This is the default locale.
		Rule::LENGTH_RANGE => '{label} must have from {min_length} to {max_length} characters.',
		Rule::MIN_VAUE => '{label} must be greater than or equal to {min_value}.',
		Rule::REGEX => '{label} has an invalid format.',
		Rule::MAX_COUNT => '{label} must have up to {max_count} item(s).',
	)
);
$validator->setMessages( $messages );

// Now we will check the object using our rules
$problems = $validator->checkObject( $obj, $rules );
// In this moment, problems will be an empty array because all values passed.
// That is: $problems === array()

// However, lets make our rules harder, just to understand how the validation works
$rules[ 'name' ][ Rule::LENGTH_RANGE ] = array( 2, 5 ); // Max of 5
$rule[ 'friends' ][ Rule::MAX_COUNT ] = 1; // just one friend (the best one :-)

// And check again
$problems = $validator->checkObject( $obj, $rules );
// Now $problems is an array like this:
// array(
//	'name' => array( 'length_range' => 'Name must have from 2 to 5 characters.' ),
//	'friends' => array( 'max_count' => 'friends must have up to 1 item(s)' )
// )
// Which means that we have two fields with problems. The format is:
//  field => hurt rule => message
// For example, the field "name" hurt the "length_range" rule and its message is
// "Name must have from 2 to 5 characters.".
//
// If we need to know whether "name" has a problem, we just check with isset:
if ( isset( $problems[ 'name' ] ) ) {
	echo 'Name has a problem', PHP_EOL;
}
// If we are only interested in the messages, and don't care about the fields,
// we just use the ProblemsTransformer
$messages = ( new ProblemsTransformer() )->justTheMessages( $problems );
var_dump( $messages );
// Will print something like:
// array( 'Name must have from 2 to 5 characters.', 'friends must have up to 1 item(s)' )
//
// That's it for now. Enjoy it!

功能

  • 验证基本类型(见示例 1
  • 验证数组(见示例 2
  • 验证动态对象(stdClass)(见示例 3
  • 验证具有私有或受保护属性的(用户自定义类)的对象(见示例 3
  • 支持本地化验证消息(不同区域设置)
  • 支持不同的字符串格式(UTF,ISO-8859-1,ASCII等)

可用规则

  • required
  • min_length
  • max_length
  • length_range
  • min_value
  • max_value
  • value_range
  • min_count(用于数组)
  • max_count(用于数组)
  • count_range(用于数组)
  • in(用于数组)
  • not_in(用于数组)
  • start_with(接受一个字符串或字符串数组,与“或”比较)
  • not_start_with(接受一个字符串或字符串数组,与“或”比较)
  • end_with(接受一个字符串或字符串数组,与“或”比较)
  • not_end_with(接受一个字符串或字符串数组,与“或”比较)
  • contains(接受一个字符串或字符串数组,与“或”比较)
  • not_contains(接受一个字符串或字符串数组,与“或”比较)
  • regex
  • format:允许使用格式(见可用格式
  • with:允许为子数组或子对象定义规则。
  • custom:您可以轻松添加其他规则。请参见以下内容。

添加自定义规则

// Adding a custom rule called "myRule" in which the value should be zero:
$validator->setRule( 'myRule', function( $value ) { return 0 == $value; } );

现在检查自定义规则

$value = rand( 0, 5 ); // Value to be checked, a random between 0 and 5 (inclusive)
$rules = array( 'myRule' => true ); // Rules to be checked. In this example, just "myRule".
$problems = $validator->check( $value, $rules ); // check() will return the hurt rules
echo isset( $problems[ 'myRule' ] ) ? 'myRule as hurt' : 'passed';

可用格式

  • anything
  • string(与anything相同)
  • name
  • word
  • alphanumeric
  • alpha
  • ascii
  • numeric
  • integer
  • double
  • float(与double相同)
  • monetary
  • price(与monetary相同)
  • tax
  • date(等于date_dmy
  • date_dmy
  • date_mdy
  • date_ymd
  • time
  • longtime
  • datetime(等于datetime_dmy
  • datetime_dmy
  • datetime_mdy
  • datetime_ymd
  • longdatetime(等于longdatetime_dmy
  • longdatetime_dmy
  • longdatetime_mdy
  • longdatetime_ymd
  • email
  • http
  • url
  • ip
  • ipv4
  • ipv6
  • custom:您可以轻松添加其他规则。请参见以下内容。

您可以指定基于日期的格式的分隔符。默认为"/",例如“31/12/1999”。

添加自定义格式

// Adding a format "myFormat" in which the value should start with "https://"
$validator->setFormat( 'myFormat', function( $value ) {
	return mb_strpos( $value, 'https://' ) === 0;
	} );

现在检查格式

$value = 'http://non-https-site.com';
$rules = array( Rule::FORMAT => 'myFormat' ); // rules to be checked
$problems = $validator->check( $value, $rules ); // check() returns the hurt rules
echo isset( $problems[ Rule::FORMAT ] ) ? 'myFormat as hurt' : 'passed';

消息替换

  • {min_length}显示最小长度;
  • {max_length}显示最大长度;
  • {length_range} 表示最小和最大长度(例如,“5-10”);
  • {min_value} 表示最小值;
  • {max_value} 表示最大值;
  • {value_range} 表示最小和最大值(例如,“5-10”);
  • {min_count} 表示最小计数;
  • {max_count} 表示最大计数;
  • {count_range} 表示最小计数和最大计数(例如,“5-10”);
  • {in} 表示由逗号分隔的项目集合;
  • {not_in} 表示由逗号分隔的项目集合;
  • {start_with} 表示字符串或由逗号分隔的字符串集合;
  • {not_start_with} 表示字符串或由逗号分隔的字符串集合;
  • {end_with} 表示字符串或由逗号分隔的字符串集合;
  • {not_end_with} 表示字符串或由逗号分隔的字符串集合;
  • {contains} 表示字符串或由逗号分隔的字符串集合;
  • {not_contains} 表示字符串或由逗号分隔的字符串集合;
  • {regex} 表示定义的正则表达式;
  • {label} 表示定义的标签,如果已定义。否则,显示数组键或对象属性名称;
  • {value} 表示值。

注意

  • {min_value}{max_value} 在使用 {value_range} 时可用;
  • {min_length}{max_length} 在使用 {length_range} 时可用;
  • {min_count}{max_count} 在使用 {count_range} 时可用。

更多

  • 支持UTF-8和其他常见格式(ISO-8859-1、Windows-1251、ASCII等);
  • 错误消息和格式可以通过区域设置指定;
  • 错误消息和格式可以一次性指定。例如,您可以从中读取JSON文件;
  • 可以不扩展任何类就指定格式和规则;
  • 类使用流畅接口(即您需要输入更少的内容);
  • 可用的构建类(即将推出);

测试

见此处.

示例

查看所有

ex1.php - 验证值

ex2.php - 验证数组

ex3.php - 验证对象