behance / nbd.php-validation
此包已被 废弃 且不再维护。未建议替代包。
NBD.php 验证组件
2.3.0
2018-05-15 22:16 UTC
Requires
- php: ^7.0
Requires (Dev)
- phpunit/phpunit: ~6
README
NBD.php - 验证组件
提供易于使用的规则来检查各种数据类型。规则可以单独使用,也可以链接在一起,用于表单验证界面。
用法
快速验证单个数据点
use Behance\NBD\Validation\Rules\IntegerRule;
$rule = new IntegerRule();
$valid = $rule->isValid( 123 ); // true
$valid = $rule->isValid( 'abc' ); // false
验证类似HTML表单的复杂键值数组“笼中”数据
use Behance\NBD\Validation\Services\ValidatorService;
$validator = new ValidatorService();
// Define a series of rules: field key, field name, and a pipe-separated sequence of validator rules (from list below)
$validator->setRule( 'email', 'E-Mail', 'required|email' )
->setRule( 'first_name', 'First Name', 'required|alpha' )
->setRule( 'last_name', 'Last Name', 'required|alpha' )
->setRule( 'middle_i', 'Middle Initial', 'alpha|nullable|maxLength[1]' );
// Insert data to be validated
$validator->setCageData( $_POST );
// Obtain a single result for whether this data set passes the defined rules
$valid = $validator->run();
if ( !$valid ) {
// Loop through the failing fields
$errors = $validator->getAllFieldErrorMessages();
foreach ( $errors as $field => $message ) {
// ...
}
// Retrieves an error message string for all failed fields
$error_message = $validator->getAllFieldErrorMessagesString();
// Retrieves the unrendered error templates for all failed fields
$error_message = $validator->getAllFieldErrorTemplates();
// Retrieves the context for a given field error
$error_context = $validator->getFieldErrorContext( $field );
// Just retrieve the error message for email field
$email_message = $validator->getFieldErrorMessage( 'email' );
// Just retrieve the field keys that failed
$error_keys = $validator->getFailedFields();
} // if !valid
else {
// As a convenience, valid data points are available as magic properties
$email = $validator->email;
$first_name = $validator->first_name;
$last_name = $validator->last_name;
// You can check if a magic property exists using isset() whether or not it has passed validation.
$has_middle = isset( $validator->middle_i );
// Or, retrieve valid fields as a key-value array
$fields = $validator->getValidData(); // ex. [ 'email' => xxx, ... ], will discard unvalidated/failed fields
// Triple check that a field is valid
$email_valid = $validator->isFailed( 'email' ); // false
$field_name = $validator->getFieldName( $key ); // E-Mail
} // else (valid)
可用的 '简单' 验证规则(且在增长中)
- alpha
- alphaNumeric
- array
- decimal
- float
- hexColor
- postitiveInteger
- integer
- json
- notEmpty
- phone
- string
- url
- nestedArray
可用的参数化验证规则
参数在规则后面用逗号分隔的方括号内定义
规则 | 用法 | 参数 | 说明 |
---|---|---|---|
matches | matches[target] | 1 | 输入是否与具有 'target' 键的参数值匹配 |
minLength | minLength[5] | 1 | 字符串输入长度是否大于等于5个字符(默认UTF-8,不是字节计数) |
maxLength | maxLength[5] | 1 | 字符串输入长度是否小于等于5个字符(默认UTF-8,不是字节计数) |
instanceOf | instanceOf[stdClass] | 1 | 输入是否为对象,且类型为 'stdClass' |
range | range[1,10] | 2 | 输入是否在1和10之间(包含1和10) |
stringContains | stringContains[haystack] | 1 | 输入是否为字符串,且是 'haystack' 的“针” |
callback | callback[User,isUniqueEmail] | 2 | 调用 User::isUniqueEmail($input),将结果解释为布尔值 |
containedIn | containedIn[abc,def,ghi] | 1+ | 输入是否在参数数组中(可变长度) |
特殊参数化规则
规则 | 用法 | 参数 | 说明 |
---|---|---|---|
filter | filter[trim,md5] | 1+ | 应用输入的转换,评估参数从左到右,转换由后续规则和后续检索看到。参数可以是任何返回转换结果的单一参数定义函数。例如,使用 `filter[trim,md5]` 将先 trim(),然后 md5() 输入,这将编码为 md5(trim($input))。在验证规则中的 filter 位置很重要,因为整个验证规则也是从左到右评估的。(例如:在 `notEmpty` 之前调用 `filter[trim]` 将在检查是否为空之前修剪输入)。 |
其他特殊规则
规则 | 说明 |
---|---|
required | 所需规则检查一个字段是否传递给了验证器。它**不**验证字段值,以及它是否为空或不是。 |
可空 | 可空规则允许传递空数据来模拟清除字段数据。它接受空字符串或`NULL`作为有效输入。 |
示例
情况 | 有效 |
---|---|
必需的可空,其中键不存在 | false |
必需的可空,其中键存在但值设置为空字符串/null | true |
必需的可空,其中键是真值 | true |
可选的可空,其中键不存在 | true |
可选的可空,其中键存在但值设置为空字符串/null | true |
可选的可空,其中键是真值 | true |
- 有效的“有效”情况仍然取决于规则集的其余部分
- 特殊规则不能单独或与其他规则一起单独使用,它们必须与其他规则一起使用。
快速轻松地添加自定义命名验证器
use Behance\NBD\Validation\Services\ValidatorService;
$validator = new ValidatorService();
$rules = $validator->getRulesProvider();
// Creates a rule that can be used independently, or as part of the validator service
$regex_rule = $rules->setRegexRule( 'myNewRegexRule', '/^abcdefg$/' );
$valid = $regex_rule->isValid( 'abcdefg' ); // true
// Create a callback rule based on a boolean-returning closure, can also be used in both places
$closure = ( function( $data ) {
return $data == 'hello';
} );
$callback_rule = $rules->setCallbackRule( 'hello', $closure );
$callback_rule->isValid( 'hello' ); // true
#####递归规则
nestedArray
规则接受一个额外的第四个参数,即规则数组
use Behance\NBD\Validation\Services\ValidatorService;
$validator = new ValidatorService();
$validator->setRules( [
[ 'email', 'E-Mail', 'required|email' ],
[ 'name', 'Name', 'nestedArray',
[
[ 'first_name', 'First Name', 'required|alpha' ],
[ 'last_name', 'Last Name', 'required|alpha' ],
[ 'middle_i', 'Middle Initial', 'alpha|nullable|maxLength[10]' ]
]
]
] );
also can set using setNestedRule:
$validator->setNestedRule( [ 'name', 'Name', 'nestedArray',
[
[ 'first_name', 'First Name', 'required|alpha' ],
[ 'last_name', 'Last Name', 'required|alpha' ],
[ 'middle_i', 'Middle Initial', 'alpha|nullable|maxLength[10]' ]
]
] );
$validator->runStrict();
$validated_data = $validator->getValidatedData();
$email = $validated_data['email'];
$first_name = $validated_data['name']['first_name'];
$last_name = $validated_data['name']['last_name'];
$middle_i = $validated_data['name']['middle_i'];