ajd / ajd-validation
简单的PHP验证库
Requires
- php: >=7.3
- egulias/email-validator: ~2.1
This package is auto-updated.
Last update: 2024-09-05 08:28:33 UTC
README
简单的PHP验证和过滤库
描述
PHP验证和过滤库。
入门指南
依赖项
- egulias/email-validator : 2.1
安装
- composer require ajd/ajd-validation
作者
贡献者姓名和联系方式
Aj Doc (thedoctorisin17@gmail.com)
版本历史
- 0.1 (master)
- 初始发布
文档
用法
在本文档中,我们将了解如何使用ajd-validation。
基本用法
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(5) ->check('firstname', 'value-of-firstname'); $v ->required() ->minlength(5) ->check('lastname', [ 'lastname' => 'value-of-lastname' ] ); // validation will automatically validate one dimensional array $v ->required() ->minlength(5) ->check('list_of_item', [ 'list_of_item' => [ 'apples', '', 'b' ] ] ); if($v->validation_fails()) { var_dump($v->errors()->all()); echo $v->errors()->toStringErr(); } try { $v ->required() ->minlength(5) ->check('firstname', 'value-of-firstname'); $v ->required() ->minlength(5) ->check('lastname', [ 'lastname' => 'value-of-lastname' ] ); $v ->required() ->minlength(5) ->check('middlename', 'value-of-middlename'); $v->assert(); } catch(Exception $e) { echo $e->getMessage(); }
您可以通过链式方式定义规则,如示例所示,定义所有规则后,您可以调用check方法开始验证,该方法接收字段键或字段名作为第一个参数,以及作为第二个参数的值或值的数组,如上面的示例所示。
如果验证失败,validation_fails方法将返回true,可以通过$v->errors()->all()
获取错误消息,该方法将返回一个字段和规则错误消息的关联数组,或者您可以使用$v->errors()->toStringErr()
获取格式化的错误消息。
或者,您可以将字段-规则定义包装在try catch中,在定义所有规则后使用$v->assert()
,这将抛出一个包含错误消息的异常。
验证将自动将所有定义的规则应用于一维数组。
一些有用的方法API
* $v->validation_fails($field_key = null, $array_key = null);
- validation fails can accept field key if you want to check if field validation fails
- validation fails can also accept field key and the specific key in a one dimesional array to check if that specific item in the array fails
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(5) ->check('firstname', ''); $v ->required() ->minlength(5) ->check('lastname', [ 'lastname' => 'value-of-lastname' ] ); // validation will automatically validate one dimensional array $v ->required() ->minlength(5) ->check('list_of_item', [ 'list_of_item' => [ 'apples', '', 'b' ] ] ); var_dump($v->validation_fails('firstname')); // will return true var_dump($v->validation_fails('lastname')); // will return false var_dump($v->validation_fails('list_of_item', 0)); // will return true var_dump($v->validation_fails('list_of_item', 1)); // will return false var_dump($v->validation_fails('list_of_item', 2)); // will return false
- $v->check($field, mixed $value); - check可以接受字段作为第一个参数 - 字段也可以用管道符号分隔,管道符号后面的字符串将用作错误消息中的字段名。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required() ->check('firstname', ''); // Outputs Firstname is required. $v->required() ->check('firstname|First Name', ''); // Outputs First Name is required.
- value
- can be a string
- numeric
- array [1,2,3]
- array [$field => 'field_value'], [$field => 1], [$field => [1,2,3] ]
-
$v->assert($addHeaderErrorMessage = true) : \Exception
- assert将抛出一个包含所有错误消息的异常
- 如果$addHeaderErrorMessage = true,将添加“所有必需的规则都必须通过才能为“[字段]”。”的消息
- assert将抛出一个包含所有错误消息的异常
-
$v->assertFirst($addHeaderErrorMessage = true) : \Exception
- assertFirst将抛出一个包含第一个错误消息的异常
- 如果$addHeaderErrorMessage = true,将添加“所有必需的规则都必须通过才能为“[字段]”。”的消息
- assertFirst将抛出一个包含第一个错误消息的异常
反转结果
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->Notrequired() ->check('firstname', ''); // doesn't output error.
您可以通过在规则名前加Not
后跟规则名来反转验证。不输出错误,但如果您设置值,它将在下面输出错误。
All of the required rules must pass for "Middlename2".
- The Middlename2 field is not required.
在定义规则时使用或逻辑
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->oRminlength(2) ->oRdigit() ->oRcompare('==', 'b') ->check('middlename2', 'a');
上面的示例将输出错误
All of the required rules must pass for "Middlename2".
- Middlename2 must be greater than or equal to 2. character(s).
- Middlename2 must contain only digits (0-9).
- Middlename2 must be equal to "b".
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->oRminlength(2) ->oRdigit() ->oRcompare('==', 'b') ->check('middlename2', 'aa');
但如果验证通过任何定义的规则,它将不会输出错误。基本来说,这个定义意味着如果任何规则通过,字段就通过。
传递多个字段
- 当一些字段具有相同的验证定义时很有用
- 您可以在
$v->check([fields])
中传递一个字段数组,验证将尝试查找并将字段映射到值(如果值是一个键值对数组)。如果值不是数组,它将重复为字段进行验证。 - 请注意,这将组合所有字段的承诺和验证结果,因此如果其中一个字段失败,承诺和验证结果都将失败。
use AJD_validation\AJD_validation; $v = new AJD_validation; $arr3 = ['field1' => '', 'field2' => '']; $v11 = $v ->required() ->minlength(2) ->check(['field1', 'field2'], $arr3); //prints error /* All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). All of the required rules must pass for "Field2". - The Field2 field is required - Field2 must be greater than or equal to 2. character(s). */
基本错误消息自定义
例如,如果您想按规则自定义错误消息,可以通过->[rulename](null, '@custom_error_Place your custom error message here')
实现。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->minlength(2) ->digit() ->compare('==', 'b', '@custom_error_"b" is the value for middlename2 to be accepted.') ->check('middlename2', 'a');
规则比较将输出以下错误
All of the required rules must pass for "Middlename2".
- Middlename2 must be greater than or equal to 2. character(s).
- Middlename2 must contain only digits (0-9).
- "b" is the value for middlename2 to be accepted.
错误自定义
- 我们可以通过使用来按规则自定义错误
$v->required() ->getInstance() ->setCustomErrorMessage([ 'overrideError' => 'override message' 'appendError' => 'appended message', ]);
- 使用
appendError
将消息附加到默认错误信息。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required() ->getInstance() ->setCustomErrorMessage([ 'appendError' => 'appended message', ]) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - The Test format field is required appended message. at row 1. - The Test format field is required appended message. at row 2. */
- 使用
overrideError
将覆盖默认错误信息。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required() ->getInstance() ->setCustomErrorMessage([ 'overrideError' => 'override message', ]) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - override message at row 1. - override message at row 2. */
- 结合使用
appendError
和overrideError
。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required() ->getInstance() ->setCustomErrorMessage([ 'overrideError' => 'override message', 'appendError' => 'appended message', ]) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - override message appended message. at row 1. - override message appended message. at row 2. */
- 当定义
@custom_error_[message]
时,不会使用overrideError
。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required(null, '@custom_error_Custom error message') ->getInstance() ->setCustomErrorMessage([ 'overrideError' => 'override message', 'appendError' => 'appended message', ]) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - Custom error message. appended message. at row 1. - Custom error message. appended message. at row 2. */
使用格式化器自定义错误信息
- 我们可以通过使用格式化器来按规则自定义错误信息
$v->required() ->getInstance() ->setFormatter(\Closure|\AJD_validation\Formatter\FormatterInterface::class, 可选 $formatterOptions);
\Closure
和(\AJD_validation\Formatter\FormatterInterface::class)->format()
将接收string $message
- 默认规则错误信息。\AJD_validation\Contracts\Abstract_exceptions::class $exception
- 规则异常类。string $field = null
- 当前字段。array $satisfier = null
- 规则满足条件。mixed $value = null
- 当前给定的值。
\Closure
和(\AJD_validation\Formatter\FormatterInterface::class)->format()
可以通过$this->getOptions()
访问额外的格式化器选项。- 默认选项是
string cus_err
- 通过@custom_error_[message]
传递的。int valueKey
- 值的当前索引。string clean_field
- 当前格式化字段名。string orig_field
- 当前预格式化字段名。
\Closure
示例。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required() ->getInstance() ->setFormatter(function($message, $exceptionObj, $field, $satisfier = null, $value = null) { $realMessage = $this->getOptions()['cus_err'] ?: $message; return $realMessage.' custom at '.$this->getOptions()['valueKey'] + 1; }) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - The Test format field is required custom at 1 at row 1. - The Test format field is required custom at 2 at row 2. */
- 使用
Formatter Class
和格式化器选项以及$satisfier
示例。
use AJD_validation\AJD_validation; namespace AJD_validation\Formatter; use AJD_validation\Formatter\AbstractFormatter; use AJD_validation\Contracts\Abstract_exceptions; class RequiredFormatter extends AbstractFormatter { public function format(string $messages, Abstract_exceptions $exception, $field = null, $satisfier = null, $value = null) { $options = $this->getOptions(); $cnt = $options['valueKey'] ?? 0; $satis_str = $satisfier[0] ?? ''; $cnt = $cnt + 1; $addtional_option = $options['addtional'] ?? ''; $message = 'This :field is required at row {cnt} with a satisfier of. '.$satis_str.' '.$addtional_option.'.'; $message = $exception->replaceErrorPlaceholder(['cnt' => $cnt], $message); return $message; } } $v = new AJD_validation; $v->required(1) ->getInstance() ->setFormatter(\AJD_validation\Formatter\RequiredFormatter::class, ['addtional' => 'addtional']) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - This Test format is required at row 1 with a satisfier of. 1 addtional. at row 1. - This Test format is required at row 2 with a satisfier of. 1 addtional. at row 2. */
- 结合使用
appnedError
。
use AJD_validation\AJD_validation; namespace AJD_validation\Formatter; use AJD_validation\Formatter\AbstractFormatter; use AJD_validation\Contracts\Abstract_exceptions; class RequiredFormatter extends AbstractFormatter { public function format(string $messages, Abstract_exceptions $exception, $field = null, $satisfier = null, $value = null) { $options = $this->getOptions(); $cnt = $options['valueKey'] ?? 0; $satis_str = $satisfier[0] ?? ''; $cnt = $cnt + 1; $addtional_option = $options['addtional'] ?? ''; $message = 'This :field is required at row {cnt} with a satisfier of. '.$satis_str.' '.$addtional_option.'.'; $message = $exception->replaceErrorPlaceholder(['cnt' => $cnt], $message); return $message; } } $v = new AJD_validation; $v->required(1) ->getInstance() ->setFormatter(\AJD_validation\Formatter\RequiredFormatter::class, ['addtional' => 'addtional']) ->setCustomErrorMessage([ 'appendError' => 'append message' ]) ->check('test_format', [ 'test_format' => ['', '']]); //prints error /* All of the required rules must pass for "Test format". - This Test format is required at row 1 with a satisfier of. 1 addtional. append message. at row 1. - This Test format is required at row 2 with a satisfier of. 1 addtional. append message. at row 2. */
设置错误消息语言
- 要设置错误消息语言,请使用
$v->setLang(Lang::FIL);
use AJD_validation\AJD_validation; use AJD_validation\Constants\Lang; $v = new AJD_validation; $v->setLang(LANG::FIL); $v ->required() ->check('field', ''); /* Outputs error The Field field ay kelangan */
- 检查src\AJD_validation\Constants\Lang.php了解当前支持的语言
- 注意,并非所有规则都支持本地化,将逐步添加本地化支持 :))
添加自定义Lang文件
- 您可以选择添加自己的自定义lang文件
use AJD_validation\AJD_validation; use AJD_validation\Constants\Lang; $v = new AJD_validation; $v->addLangDir('example', __DIR__.DIRECTORY_SEPARATOR.'custom_lang/', true); $v->setLang('example');
$v->addLangDir(string $lang, string $fullPath, bool $createWrite = false)
- 第一个参数是语言名称,也是lang文件名,后面附加
_lang
。所以在上面的示例中,lang文件名必须是example_lang.php
- 第二个参数是lang文件所在的完整路径/目录。
- 第三个参数是$createWrite,默认为false,如果设置为true,ajd validation将在不存在时创建$fullPath,如果不存在,将创建lang文件,并为所有可用的规则生成当前使用的错误信息,以便您可以按需编辑文件。
- 第一个参数是语言名称,也是lang文件名,后面附加
checkArr方法
->checkArr(string $field, array $value)
- 方法允许通过点符号进行数组遍历验证
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->digit() ->checkArr('arr.*', [ 'arr' => [ 'arr1' => [ 'sub_arr' => 'a', 'sub_arr2' => ['', ''] ], 'arr2' => [] ] ]); /* Outputs error All of the required rules must pass for "Arr.arr1.sub arr". - Arr.arr1.sub arr must contain only digits (0-9). All of the required rules must pass for "Arr.arr1.sub arr2.0". - The Arr.arr1.sub arr2.0 field is required - Arr.arr1.sub arr2.0 must contain only digits (0-9). All of the required rules must pass for "Arr.arr1.sub arr2.1". - The Arr.arr1.sub arr2.1 field is required - Arr.arr1.sub arr2.1 must contain only digits (0-9). All of the required rules must pass for "Arr.arr2". - The Arr.arr2 field is required - Arr.arr2 must contain only digits (0-9). */ $v ->required() ->digit() ->checkArr('arr.arr1', [ 'arr' => [ 'arr1' => [ 'sub_arr' => 'a', 'sub_arr2' => ['', ''] ], 'arr2' => [] ] ]); /* Outputs error All of the required rules must pass for "Arr.arr1.sub arr". - Arr.arr1.sub arr must contain only digits (0-9). All of the required rules must pass for "Arr.arr1.sub arr2.0". - The Arr.arr1.sub arr2.0 field is required - Arr.arr1.sub arr2.0 must contain only digits (0-9). All of the required rules must pass for "Arr.arr1.sub arr2.1". - The Arr.arr1.sub arr2.1 field is required - Arr.arr1.sub arr2.1 must contain only digits (0-9). */ $v ->required() ->digit() ->checkArr('arr.arr1.sub_arr', [ 'arr' => [ 'arr1' => [ 'sub_arr' => 'a', 'sub_arr2' => ['', ''] ], 'arr2' => [] ] ]); /* Outputs error All of the required rules must pass for "Arr.arr1.sub arr". - Arr.arr1.sub arr must contain only digits (0-9). */ $v ->required() ->digit() ->checkArr('arr.arr1.sub_arr2', [ 'arr' => [ 'arr1' => [ 'sub_arr' => 'a', 'sub_arr2' => ['', ''] ], 'arr2' => [] ] ]); /* Outputs error All of the required rules must pass for "Arr.arr1.sub arr2.0". - The Arr.arr1.sub arr2.0 field is required - Arr.arr1.sub arr2.0 must contain only digits (0-9). All of the required rules must pass for "Arr.arr1.sub arr2.1". - The Arr.arr1.sub arr2.1 field is required - Arr.arr1.sub arr2.1 must contain only digits (0-9). */ $v ->required() ->checkArr('arr.arr2', [ 'arr' => [ 'arr1' => [ 'sub_arr' => '', 'sub_arr2' => ['', ''] ], 'arr2' => [] ] ]); /* Outputs error All of the required rules must pass for "Arr.arr2". - The Arr.arr2 field is required */
重用规则定义
- 通过以下方式重用或存储规则定义:
use AJD_validation\AJD_validation; $v = new AJD_validation; $v1 = $v ->required() ->minlength(3) ->maxlength(30) ->setUpValidation() ->getValidationDefinition(); $v2 = $v ->required() ->minlength(2) ->setUpValidation() ->getValidationDefinition(); $v1()->check('field1', 'e'); $v2()->check('field2', ''); $v1()->digit()->check('field3', '');
- 我们可以通过使用
$v->setUpValidation((可选)'[唯一标识符]')->getValidationDefinition()
来重用规则定义,将其存储在变量中,然后像函数一样调用该变量,如上面的示例所示。 - 我们可以为特定字段(如'field3')定义另一个不在存储中的规则定义。
任何
- 使用此功能来模拟两个或更多验证定义之间的
or
逻辑。 - 如果任何一个验证通过,则验证将通过。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->any( $v->required()->minlength(2)->check('or_field1',['or_field1' => ['', '']]), $v->required()->check('or_field2',['or_field2' => ['']]), $v->required()->check('or_field3',''), ); // validation fails /* Outputs error All of the required rules must pass for "Or field1". - The Or field1 field is required at row 1. - The Or field1 field is required at row 2. - Or field1 must be greater than or equal to 2. character(s). at row 1. - Or field1 must be greater than or equal to 2. character(s). at row 2. All of the required rules must pass for "Or field2". - The Or field2 field is required at row 1. All of the required rules must pass for "Or field3". - The Or field3 field is required */ $v->any( $v->required()->minlength(2)->check('or_field1',['or_field1' => ['', '']]), $v->required()->check('or_field2',['or_field2' => ['']]), $v->required()->check('or_field3','a'), ); // validation passes /* Note: in first validation even if one item in or_field1 passes it will still fail and print error, to make this validation pass both item in or_field1 must pass */ /* Example 2 */ $v->any( $v->required()->check('group_and_single1', ''), $v ->Srequired(null, AJD_validation::LOG_OR) ->field('group_and_single2') ->field('group_and_single3') ->minlength(2) ->eSrequired() ->checkGroup( [ 'group_and_single2' => '', 'group_and_single3' => '', ] ) ); // validation fails /* Outputs error All of the required rules must pass for "Group and single1". - The Group and single1 field is required All of the required rules must pass for "Group and single2". - The Group and single2 field is required All of the required rules must pass for "Group and single3". - The Group and single3 field is required - Group and single3 must be greater than or equal to 2. character(s). */ $v->any( $v->required()->check('group_and_single1', ''), $v ->Srequired(null, AJD_validation::LOG_OR) ->field('group_and_single2') ->field('group_and_single3') ->minlength(2) ->eSrequired() ->checkGroup( [ 'group_and_single2' => '', 'group_and_single3' => 'aa', ] ) ); // validation passes /* Note: since we define in `->Srequired(null, AJD_validation::LOG_OR)` that `group_and_single2` or `group_and_single3` passes required and field `group_and_single3` passes minlength(2) this any validation passes. */
触发条件
- 使用此功能在条件为真时触发验证。
- 如果您不喜欢编写if条件,请使用此功能。
- 当triggerWhen返回true时,将运行验证;如果为false,则不会运行验证。
use AJD_validation\AJD_validation; $v = new AJD_validation; /* Instead of */ if(!empty($test)) { $v ->required() ->minlength(2) ->check('trigger_when', ''); } /* you can write */ $v ->required() ->minlength(2) ->triggerWhen(!empty($test)) ->check('trigger_when', ''); /* triggerWhen can receive the following arguments */ // 1. booleans $v ->required() ->minlength(2) ->triggerWhen(!empty($test)) // boolean ->check('trigger_when', ''); $v ->required() ->minlength(2) ->triggerWhen($v->getValidator()->validate('')) // boolean ->check('trigger_when', ''); $v ->required() ->minlength(2) ->triggerWhen($v->Lgfirst(true)->runLogics('')) // boolean ->check('trigger_when', ''); // 2. callables $v ->required() ->minlength(2) ->triggerWhen(function($ajdInstance) { return true; }) // callable ->check('trigger_when', ''); class Test { public function handle($ajdInstance, mixed...$ags) { /* $ags[0] = 1 $ags[1] = 2 */ return true; } } $v ->required() ->minlength(2) ->triggerWhen([new Test, 'handle', 1, 2]) // callable ->check('trigger_when', ''); // 3. Validator instance // will validate value $v ->required() ->minlength(2) ->triggerWhen($v->getValidator()->required()) // Validator instance ->check('trigger_when', ''); // 4. Logics_map instance // will validate value $v ->required() ->minlength(2) ->triggerWhen($v->Lgfirst(true)->wrapLogic()) // Logics_map instance ->check('trigger_when', '');
$v->triggerWhen(bool|callable|\AJD_validation\Helpers\Logics_map|\AJD_validation\Contracts\Validator)
验证结果对象
- 验证结果是一个对象,可以从中获取验证结果,例如错误、值、验证定义,并允许对结果进行一些处理。
- 要获取验证结果
use AJD_validation\AJD_validation; $v = new AJD_validation; // 1 During setup $v ->required() ->setUpValidation() // returns validation result object // 2 after validation $v ->required() ->minlength(2) ->check('field1', '') ->getValidationResult() // returns validation result object
- 映射错误
- 使用
->mapErrors(\Closure(string $errors, self $that) : array)
mapErrors
仅在验证失败时触发。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(2) ->check('field1', '') ->getValidationResult() ->mapErrors(function($errors, $self) { echo '<pre>'; print_r($errors); return $errors; }); // prints /* Array ( [required] => Array ( [0] => The Field1 field is required ) [minlength] => Array ( [0] => Field1 must be greater than or equal to 2. character(s). ) ) */
- 在
mapErrors
中覆盖消息
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(2) ->check('field1', '') ->getValidationResult() ->mapErrors(function($errors, $self) { $mm = ''; $mArr = []; foreach($errors as $rule => $mess) { foreach($mess as $k => $m) { $mm .= ' - '.$m.' Custom error new<br>'; $self->overrideErrorMessage($mm, $rule, $k); } } return $errors; }); // prints errors /* All of the required rules must pass for "Field1". - - The Field1 field is required Custom error new - Field1 must be greater than or equal to 2. character(s). Custom error new */
- 在
mapErrors
中抛出错误
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(2) ->check('field1', '') ->getValidationResult() ->mapErrors(function($errors, $self) { $mm = ''; $mArr = []; foreach($errors as $rule => $mess) { foreach($mess as $k => $m) { $mm .= ' - '.$m.' Custom error new<br>'; $self->overrideErrorMessage($mm, $rule, $k); } } return $self->throwErrors($mm); })->otherwise(function($e) { echo $e->getMessage().'from otherwise throw'; }); // prints errors /* - The Field1 field is required Custom error new - Field1 must be greater than or equal to 2. character(s). Custom error new from otherwise throw */
- 映射值
- 使用
->mapValue(\Closurea(mixed $values, self $that) : mixed)
mapValue
仅在验证通过时触发。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(2) ->check('field1', 'aa') ->getValidationResult() ->mapValue(function($value, $self) { echo '<pre>'; print_r($value); return $value; }); // prints value /* Array ( [0] => aa ) */ // Do some processing echo '<pre>'; print_r($v ->required() ->minlength(2) ->check('field1', 'aa') ->getValidationResult() ->mapValue(function($value, $self) { return ['field1' => $value[0]]; })->getFieldValue()); /* returns Array ( [field1] => aa ) */
- 前向解析
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->minlength(2) ->check('field1', 'aa') ->getValidationResult() ->mapValue(function($value, $self) { $val = ['field1' => $value[0]]; return \AJD_validation\Async\PromiseHelpers::resolve($val); })->done(function($value) { print_r($value); })->then(function($v) { echo 'test forward resolution'.var_export($v, true); }); /* prints Array ( [field1] => aa ) test forward resolutionarray ( 'field1' => 'aa', ) */
- 获取字段值
- 使用
->getFieldValue() : mixed
getFieldValue
仅在验证通过时触发
use AJD_validation\AJD_validation; $v = new AJD_validation; $v1 = $v ->required() ->minlength(2) ->check('field1', 'aa') ->getValidationResult() ->getFieldValue(); print_r($v1); /* prints/returns Array ( [0] => aa ) */ // if validation fails $v1 = $v ->required() ->minlength(2) ->check('field1', '') ->getValidationResult() ->getFieldValue(); print_r($v1); /* prints/returns Array () */
- 获取所有有效值
- 使用
->getValue(array &$storage) : array
getValue
仅在验证通过时触发
use AJD_validation\AJD_validation; $v = new AJD_validation; echo '<pre>'; $result1 = $v ->required() ->minlength(2) ->check('field1', 'a1') ->getValidationResult(); $v1 = $result1->getValidationDefinition(); $result1->getValue($storage); $v1()->check('field2', '') ->getValidationResult() ->getValue($storage); $v1()->check('field3', 'a3') ->getValidationResult() ->getValue($storage); print_r($storage); /* In the above example only 'field1' and 'field3' was included in the storage because 'field2' fails. */ /* prints Array ( [field1] => a1 [field3] => a3 ) */
- 将有效值/值转换为特定类型。
use AJD_validation\AJD_validation; $v1 = $v ->required() ->minlength(2) ->check('field1', 'aa') ->getValidationResult() ->castValueTo('int') ->getFieldValue(); print_r($v1); /* prints to Array ( [0] => 0 ) */ $result1 = $v ->required() ->minlength(2, true, true) ->check('field1', '2022-01-01') ->getValidationResult(); $v1 = $result1->getValidationDefinition(); $result1->castValueTo('DateTime')->getValue($storage); $v1()->check('field2', '') ->getValidationResult() ->getValue($storage); $v1()->check('field3', 'true') ->getValidationResult() ->castValueTo('bool') ->getValue($storage); print_r($storage); /* prints Array ( [field1] => DateTime Object ( [date] => 2022-01-01 00:00:00.000000 [timezone_type] => 3 [timezone] => Europe/Berlin ) [field3] => 1 ) */
- 检查验证是否有效。
- 使用
->isValid() : bool
use AJD_validation\AJD_validation; $v = new AJD_validation; $result1 = $v ->required() ->minlength(2) ->check('field1', 'a1') ->getValidationResult() ->isValid(); var_dump($result1); /* prints/returns bool(true) */
组合器
- 组合器允许您组合字段规则验证定义,这将允许为组合验证定义创建错误消息,允许按顺序检查规则集,允许按顺序检查字段规则集,这将允许关联检查组合验证定义。
- 组合字段规则定义
use AJD_validation\AJD_validation; $v = new AJD_validation; // first way $combined = $v->combinator( $v->required() ->minlength(2) ->check('field1', '') ->getValidationResult(), $v->required() ->minlength(3) ->check('field2', '') ->getValidationResult(), ); var_dump($combined->check('') ->getValidationResult() ->isValid()); // returns/prints false // prints error /* All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). All of the required rules must pass for "Field2". - The Field2 field is required - Field2 must be greater than or equal to 3. character(s). */ // second way // only difference from the first way is that with this way it won't run the validation and remove error message. $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); var_dump($combined->check('') ->getValidationResult() ->isValid()); // returns/prints false // prints error /* All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). All of the required rules must pass for "Field2". - The Field2 field is required - Field2 must be greater than or equal to 3. character(s). */
- 组合组合字段规则验证的错误消息。
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined->setCombineErrorMessage('field 1 and field 2 is required and field 1 min length is 2 while field 2 min length is 3.')->check(''); $v->assert(); // prints error /* field 1 and field 2 is required and field 1 min length is 2 while field 2 min length is 3. */
- 组合验证的数组值
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined->check(['fieldcom' => ['', '']], 'fieldcom'); $v->assert(); // prints error /* All of the required rules must pass for "Field1". - The Field1 field is required at row 1. - The Field1 field is required at row 2. - Field1 must be greater than or equal to 2. character(s). at row 1. - Field1 must be greater than or equal to 2. character(s). at row 2. All of the required rules must pass for "Field2". - The Field2 field is required at row 1. - The Field2 field is required at row 2. - Field2 must be greater than or equal to 3. character(s). at row 1. - Field2 must be greater than or equal to 3. character(s). at row 2. */
- 与另一个组合器组合
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined2 = $v->combinator( $combined, $v->required() ->email() ->setUpValidation('field3') ); $combined2->check(['fieldcom' => ['', '']], 'fieldcom'); $v->assert(); // prints error /* All of the required rules must pass for "Field3". - The Field3 field is required at row 1. - The Field3 field is required at row 2. - The Field3 field must be a valid email. at row 1. - The Field3 field must be a valid email. at row 2. All of the required rules must pass for "Field1". - The Field1 field is required at row 1. - The Field1 field is required at row 2. - Field1 must be greater than or equal to 2. character(s). at row 1. - Field1 must be greater than or equal to 2. character(s). at row 2. All of the required rules must pass for "Field2". - The Field2 field is required at row 1. - The Field2 field is required at row 2. - Field2 must be greater than or equal to 3. character(s). at row 1. - Field2 must be greater than or equal to 3. character(s). at row 2. */
- 按顺序检查组合验证
- 这意味着如果第一个验证通过,它将进行下一个验证
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined->sequence(''); $v->assert(); // prints error /* All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). */ $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined->sequence('aa'); $v->assert(); // prints error /* All of the required rules must pass for "Field2". - Field2 must be greater than or equal to 3. character(s). */
- 按关联检查组合验证
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined->associative([ 'field1' => 'aa', 'field2' => '' ]); $v->assert(); // prints error /* All of the required rules must pass for "Field2". - The Field2 field is required - Field2 must be greater than or equal to 3. character(s). */
- 按关联和顺序检查组合验证
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), ); $combined->assocSequence([ 'field1' => '', 'field2' => '' ]); $v->assert(); // prints error /* All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). */ $combined->assocSequence([ 'field1' => 'aa', 'field2' => '' ]); $v->assert(); // prints error /* All of the required rules must pass for "Field2". - The Field2 field is required - Field2 must be greater than or equal to 3. character(s). */
- 按关联和分组顺序检查组合验证
- 这适用于多步表单。
use AJD_validation\AJD_validation; $v = new AJD_validation; $combined = $v->combinator( $v->required() ->minlength(2) ->setUpValidation('field1'), $v->required() ->minlength(3) ->setUpValidation('field2'), $v->required() ->minlength(5) ->setUpValidation('field3'), ); $combined->assocSequence([ 'basic_info_group' => [ 'field1' => '', 'field2' => '' ], 'account_details_group' => [ 'field3' => '' ] ]); $v->assert(); // prints error /* All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). All of the required rules must pass for "Field2". - The Field2 field is required - Field2 must be greater than or equal to 3. character(s). */ $combined->assocSequence([ 'basic_info_group' => [ 'field1' => 'aa', 'field2' => 'aaa' ], 'account_details_group' => [ 'field3' => '' ] ]); $v->assert(); // prints error /* All of the required rules must pass for "Field3". - The Field3 field is required - Field3 must be greater than or equal to 5. character(s). */
请注意,所有组合器都返回一个承诺,您也可以通过 ->getValidationResult()
获取验证结果。
客户端组件
-
请注意,AJD验证没有真正的客户端JavaScript版本,它只是通过服务器端渲染同步/端口其内置的一些规则到客户端。目前它不支持Vue、React、Svelte等JavaScript框架,但此组件使您能够创建/支持此类框架。也许通过发送JSON响应作为验证数组。
-
请注意,客户端组件目前支持以下库。
-
请注意,客户端组件仅支持以下内置规则。
$rulesClass = [ 'required', 'required_allowed_zero', // required base rules 'email', 'base_email', 'rfc_email', 'spoof_email', 'no_rfc_email', 'dns_email', // email base rules 'in', 'date', 'multiple', // rules with client side support 'alpha', 'alnum', 'digit', // ctype rules 'regex', 'mac_address', 'consonant', 'mobileno', 'phone', 'vowel', // regex rules 'maxlength', 'minlength' // length based rules ];
- 使用客户端组件
- 客户端组件默认为 parsley.js
- 必须熟悉不同规则所需的参数,请先阅读 规则。
#client_[必须与字段名相同]
- 例如
$v->required(null, '#client_field1')->check('field1', '');
- 例如
use AJD_validation\AJD_validation $v = new AJD_validation; $v->required(null, '#client_email') ->email([], '#client_email') ->in(['a@test.com', 'b@test.com'], '#client_email') ->check('email', ''); $clientSide = $v->getClientSide(); echo '<pre>'; print_r($clientSide); /* prints Array ( [customJS] => function inRuleArray(value, haystack, identical) { for (var i in haystack) { if( identical ) { if (haystack[i] === value) return true; } else { if (haystack[i] == value) return true; } } return false; } window.Parsley.addValidator('inrule', { validate: function(value, requirement, obj) { var arr = requirement.split('|+'); var identical = false; var elem = $(obj.element); var msg = $(obj.element).attr('data-parsley-in-message'); if( elem.attr('data-parsley-inrule-identical') ) { identical = true; } var check = inRuleArray(value, arr, identical); if( !check ) { return $.Deferred().reject(msg); } return inRuleArray(value, arr, identical); }, messages: { en: 'Email must be in { "a@test.com", "b@test.com" }.' } }); [rules] => Array ( ) [messages] => Array ( ) [email] => data-parsley-required="true" data-parsley-required-message="The Email field is required" data-parsley-type="email" data-parsley-type-message="The Email field must be a valid email." ) */ return $clientSide;
- 与 parsley 一起使用
<script type="text/javascript"> $(function() { <?php echo $clientSide['customJs'] ?> }); </script> <input type="text" <?php echo $clientSide['email'] ?> name="email">
- JqueryValidation 示例
use AJD_validation\AJD_validation $v = new AJD_validation; $v->required(null, '#client_email') ->email([], '#client_email') ->in(['a@test.com', 'b@test.com'], '#client_email') ->check('email', ''); echo '<pre>'; $client = $v->getClientSide(true, \AJD_validation\Helpers\Client_side::JQ_VALIDATION); print_r($client); // prints /* Array ( [customJS] => function inRuleArray(value, haystack, identical) { for (var i in haystack) { if( identical ) { if (haystack[i] === value) return true; } else { if (haystack[i] == value) return true; } } return false; } jQuery.validator.addMethod('in', function(value, element, params) { var arr = params[0].split('|+'); var identical = params[1] || false; return this.optional(element) || inRuleArray(value, arr, identical); }, 'Email must be in { "a@test.com", "b@test.com" }.'); [rules] => Array ( [email] => Array ( [required] => 1 [email] => 1 [in] => Array ( [0] => a@test.com|+b@test.com [1] => true ) ) ) [messages] => Array ( [email] => Array ( [required] => The Email field is required [email] => The Email field must be a valid email. [in] => Email must be in { "a@test.com", "b@test.com" }. ) ) ) */ return $client
- 与 jqueryvalidation 一起使用
<?php $clientSide = $client; unset($clientSide['customJS']); ?> <script type="text/javascript"> $().ready(function() { <?php if(!empty($client['customJS'])) { echo $client['customJS']; } ?> $('#yourForm').validate(<?php echo json_encode($clientSide) ?>); }); </script>
- 客户端规则
use AJD_validation\AJD_validation; $v->required(null, '#client_email') ->email([], '#client_email') ->check('email', ''); echo '<pre>'; print_r($v->getClientSide(false)); /* prints Array ( [customJS] => Array ( [0] => [1] => [2] => function inRuleArray(value, haystack, identical) { for (var i in haystack) { if( identical ) { if (haystack[i] === value) return true; } else { if (haystack[i] == value) return true; } } return false; } window.Parsley.addValidator('inrule', { validate: function(value, requirement, obj) { var arr = requirement.split('|+'); var identical = false; var elem = $(obj.element); var msg = $(obj.element).attr('data-parsley-in-message'); if( elem.attr('data-parsley-inrule-identical') ) { identical = true; } var check = inRuleArray(value, arr, identical); if( !check ) { return $.Deferred().reject(msg); } return inRuleArray(value, arr, identical); }, messages: { en: 'Email must be in { "a@test.com", "b@test.com" }.' } }); ) [clientSideJson] => Array ( ) [clientSideJsonMessages] => Array ( ) [email] => Array ( [required] => data-parsley-required="true" data-parsley-required-message="The Email field is required" [email] => data-parsley-type="email" data-parsley-type-message="The Email field must be a valid email." [in] => data-parsley-inrule='a@test.com|+b@test.com' data-parsley-inrule-identical='true' data-parsley-in-message="Email must be in { "a@test.com", "b@test.com" }." ) ) */
- 您可以在此处了解更多关于客户端的信息
验证器对象
- 要获取验证器对象,请使用
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->getValidator(); $v->getValidator()->required()->validate(''); // returns false $v->getValidator()->required()->assertErr(''); // throws an Exception
- 当使用验证器对象时,它公开
->validate(mixed $value)
方法,如果规则或规则通过,则返回 true/false->assertErr(mixed $value)
方法,如果规则或规则验证失败,则抛出异常- 此对象与 respect/validation 类似
- 这对于其他规则和使用在
->sometimes()
方法中非常有用
条件
- 如果您想有条件地运行一个规则或字段规则验证而不破坏链,请使用此方法。
->runif(bool|Closure $condtion, callable $callback = null, callable $default = null)
- 如果条件为 true,则运行回调或继续链。->runelse(bool|Closure $condtion, callable $callback = null, callable $default = null)
- 如果条件为 false,则运行回调或继续链。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->required() ->runif(false) ->minlength(2) ->check('field1', ''); /* prints error All of the required rules must pass for "Field1". - The Field1 field is required */ $v ->required() ->runif(true) ->minlength(2) ->check('field1', ''); /* prints error All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). */ $v ->required() ->runelse(function() { return true; }) ->minlength(2) ->check('field1', ''); /* prints error All of the required rules must pass for "Field1". - The Field1 field is required */ $v ->required() ->runelse(function() { return false; }) ->minlength(2) ->check('field1', ''); /* prints error All of the required rules must pass for "Field1". - The Field1 field is required - Field1 must be greater than or equal to 2. character(s). */
- 有条件地分配规则。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v ->runif(true, function($ajd) { $ajd->required(); }, function($ajd) { $ajd->minlength(2); } )->check('field1', ''); /* prints error All of the required rules must pass for "Field1". - The Field1 field is required */ $v ->runif(false, function($ajd) { $ajd->required(); }, function($ajd) { $ajd->minlength(2); } )->check('field1', ''); /* prints error All of the required rules must pass for "Field1". - Field1 must be greater than or equal to 2. character(s). */
- 使用事件/承诺示例进行条件运行验证。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->runif(true, function($ajd) { return $ajd->required()->check('field1', ''); }, function($ajd) { return $ajd->required()->check('field2', ''); } ) ->passed(function() { echo 'passed event '; }) ->fails(function($ajd, $field) { echo $field.' fails event <br/>'; }) ->done(function() { echo 'promise resolved'; }) ->otherwise(function() { echo 'promise rejected <br/>'; }); /* prints error field1 fails event promise rejected All of the required rules must pass for "Field1". - The Field1 field is required */ $v->runif(false, function($ajd) { return $ajd->required()->check('field1', ''); }, function($ajd) { return $ajd->required()->check('field2', ''); } ) ->passed(function() { echo 'passed event '; }) ->fails(function($ajd, $field) { echo $field.' fails event <br/>'; }) ->done(function() { echo 'promise resolved'; }) ->otherwise(function() { echo 'promise rejected <br/>'; }); /* prints error field2 fails event promise rejected All of the required rules must pass for "Field2". - The Field2 field is required */
- 与验证器对象一起使用
use AJD_validation\AJD_validation; $v = new AJD_validation; $result = $v ->getValidator() ->runif(false) ->email() ->runif(true) ->minlength(50) ->validate('a@t.com'); // returns false because it evaluated minlength(50) only $result = $v ->getValidator() ->runif(true) ->email() ->runif(false) ->minlength(50) ->validate('a@t.com'); // returns true because it evaluated email only and value is a valid email.
每个
- 如果您想手动遍历并应用验证到简单或嵌套数组,请使用此方法。
use AJD_validation\AJD_validation; $v = new AJD_validation; $arr = [ 'first' => '', 'second' => [ 'third' => '', 'fourth' => [ '', '' ], 'fifth' => [ 'sixth' => '', 'seventh' => '' ] ] ]; $v->each([ $v ->required() ->minlength(2) ->setUpValidation('first'), $v ->is_array() ->setUpValidation('second'), $v->each( [ $v ->required() ->minlength(3) ->setUpValidation('third'), $v ->is_array() ->setUpValidation('fourth'), $v ->each([ $v ->required() ->setUpValidation('0'), $v ->required() ->minlength(4) ->setUpValidation('1'), ]), $v ->is_array() ->setUpValidation('fifth'), $v->each([ $v->required() ->digit() ->setUpValidation('sixth'), $v->required() ->email() ->setUpValidation('seventh') ]) ] ) ])->check($arr); //prints error /* All of the required rules must pass for "First". - The First field is required. - First must be greater than or equal to 2. character(s). All of the required rules must pass for "Second.third". - The Second.third field is required. - Second.third must be greater than or equal to 3. character(s). All of the required rules must pass for "Fourth.0". - The Fourth.0 field is required. - Fourth.0 must be greater than or equal to 2. character(s). All of the required rules must pass for "Fourth.1". - The Fourth.1 field is required. - Fourth.1 must be greater than or equal to 2. character(s). All of the required rules must pass for "Fifth.sixth". - The Fifth.sixth field is required. - Fifth.sixth must contain only digits (0-9). All of the required rules must pass for "Fifth.seventh". - The Fifth.seventh field is required. - The Fifth.seventh field must be a valid email. */
$v->setUpValidation('same_array_key_on_array')
名称必须在数组上有对应的数组键。- 每次调用/嵌套
$v->each()
时,它都会遍历数组的一个级别。
- 在
$v->each()
中使用闭包。
use AJD_validation\AJD_validation; $v = new AJD_validation; $arr = [ 'first' => '', 'second' => [ 'third' => '', 'fourth' => [ '', '' ], 'fifth' => [ 'sixth' => '', 'seventh' => '' ] ] ]; $v->each([ $v ->required() ->minlength(2) ->setUpValidation('first'), $v ->is_array() ->setUpValidation('second'), $v->each( [ $v ->required() ->minlength(3) ->setUpValidation('third'), $v ->is_array() ->setUpValidation('fourth'), $v ->each([ function($ajd, $val, $field) { $options = $this->getOptions(); $parentField = $options['parentField']; $realField = $options['realField']; if($parentField == 'fourth') { return $ajd ->required() ->minlength(2) ->check($realField, $val); } } ]), $v ->is_array() ->setUpValidation('fifth'), $v->each([ $v->required() ->digit() ->setUpValidation('sixth'), $v->required() ->email() ->setUpValidation('seventh') ]) ] ) ])->check($arr); //prints error /* All of the required rules must pass for "First". - The First field is required. - First must be greater than or equal to 2. character(s). All of the required rules must pass for "Second.third". - The Second.third field is required. - Second.third must be greater than or equal to 3. character(s). All of the required rules must pass for "Fourth.0". - The Fourth.0 field is required. - Fourth.0 must be greater than or equal to 2. character(s). All of the required rules must pass for "Fourth.1". - The Fourth.1 field is required. - Fourth.1 must be greater than or equal to 2. character(s). All of the required rules must pass for "Fifth.sixth". - The Fifth.sixth field is required. - Fifth.sixth must contain only digits (0-9). All of the required rules must pass for "Fifth.seventh". - The Fifth.seventh field is required. - The Fifth.seventh field must be a valid email. */
- 使用闭包将自动迭代该级别的数组。
- 闭包将接收
$ajd
- \AJD_validation\AJD_validation实例。$val
- 当前数组值。$field
- 当前数组键。
- 闭包可以返回
$v->each()
,它是\AJD_validation\Combinators\Each
实例。$v->required()->check()
,它是\AJD_validation\Asycn\PromiseValidator
实例。$v->required()->setUpValidation('same_array_key_on_array')
,它是\AJD_validation\Asycn\ValidationResult
实例。
- 在闭包中,您可以使用以下方法
$this->getParent()
,它将返回父\AJD_validation\Combinators\Each
实例。$this->getOptions()
,它将返回一个有用的变量数组。$realField
-parent field/parent array key.'.'.current field/current array key
的连接字段名。$cnt
- 数组的当前索引。$ruleIndex
- 当前规则索引。$values
- 父数组。$parentField
- 父数组键/字段。
- 使用闭包进行自动迭代和一些条件验证的示例。
use AJD_validation\AJD_validation; $v = new AJD_validation; $arr2 = [ 'first' => [ [ '0', '0' ], [ '0' ] ], 'second' => [ [ '', 'no' ], [ 'yes' ] ] ]; $v->each([ function($ajd, $val, $field) { return $ajd ->required() ->is_array() ->check($field, $val, false); }, $v->each([ function($ajd, $val, $field) { return $ajd ->required() ->is_array() ->check($field, $val, false); }, $v->each([function($ajd, $val, $field) { $firstParent = $this->getParent()->getOptions()['parentField']; $parentOpt = $this->getParent()->getOptions(); $parentCnt = $parentOpt['cnt']; $option = $this->getOptions(); $cnt = $option['cnt']; $realField = $option['realField']; $arr2 = $this->getOrigValue(); $checkSecond = $arr2['second'][$parentCnt][$cnt]; return $ajd->required() ->sometimes(function() use($checkSecond, $firstParent) { return $checkSecond == 'yes' || $firstParent == 'second'; }) ->check($firstParent.'.'.$realField, $val); }]) ]) ])->check($arr2); // prints error /* All of the required rules must pass for "First.1.0". - The First.1.0 field is required. All of the required rules must pass for "Second.0.0". - The Second.0.0 field is required. */
- 在第一个规则/闭包中,我们只是验证数组键
first
和second
确实是一个非空数组。 - 在下一个规则/闭包中,我们向下深入一级,现在迭代
first
和second
中的两个数组,并再次验证它们确实是一个非空数组。 - 在下一个规则/闭包中,我们再次使用
$v->each()
向下深入一级,现在迭代每个first
和second
数组内的数组。在此级别,我们声明如果second
数组值是yes
或该元素来自second
数组,则要求每个元素。 - 由于
Second.1.0
==yes
且First.1.0
为零,我们打印错误。 - 由于
Secnod.0.0
==0
,我们打印错误。
- 附加错误
- 当您想显示错误发生在哪一行时很有用。
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->each([ function($ajd, $val, $field) { $options = $this->getOptions(); return $ajd->required() ->getInstance() ->setCustomErrorMessage([ 'appendError' => 'at row '.($options['cnt'] + 1) ]) ->minlength(2) ->getInstance() ->setCustomErrorMessage([ 'appendError' => 'at row '.($options['cnt'] + 1) ]) ->check('test.'.$field, $val); } ]) ->check([ '', '', '' ]); // prints error /* All of the required rules must pass for "Test.0". - The Test.0 field is required at row 1. - Test.0 must be greater than or equal to 2. character(s) at row 1. All of the required rules must pass for "Test.1". - The Test.1 field is required at row 2. - Test.1 must be greater than or equal to 2. character(s) at row 2. All of the required rules must pass for "Test.2". - The Test.2 field is required at row 3. - Test.2 must be greater than or equal to 2. character(s) at row 3. */
高级示例
- 假设您正在验证电子邮件输入,但只有第一个输入是必需的,所有输入都必须是有效的电子邮件地址,且不能重复,并且您希望当用户输入值时运行有效的电子邮件验证和不重复验证。然后您希望将字段名称'电子邮件'更改为'电子邮件列表'
use AJD_validation\AJD_validation; $v = new AJD_validation; $v->required() ->sometimes(function($value, $satisfier, $orig_field, $arrKey) { return $arrKey == 0; }) ->email()->sometimes() ->distinct()->sometimes() ->check('email|Emails', [ 'email' => ['', '', ''] ]); /*prints error All of the required rules must pass for "Emails". - The Emails field is required at row 1. */ $v->required() ->sometimes(function($value, $satisfier, $orig_field, $arrKey) { return $arrKey == 0; }) ->email()->sometimes() ->distinct()->sometimes() ->check('email|Emails', [ 'email' => ['a', '', ''] ]); /*prints error All of the required rules must pass for "Emails". - The Emails field must be a valid email. at row 1. */ $v->required() ->sometimes(function($value, $satisfier, $orig_field, $arrKey) { return $arrKey == 0; }) ->email()->sometimes() ->distinct()->sometimes() ->check('email|Emails', [ 'email' => ['a@t.com', 'a', 's'] ]); /*prints error All of the required rules must pass for "Emails". - The Emails field must be a valid email. at row 2. - The Emails field must be a valid email. at row 3. */ $v->required() ->sometimes(function($value, $satisfier, $orig_field, $arrKey) { return $arrKey == 0; }) ->email()->sometimes() ->distinct()->sometimes() ->check('email|Emails', [ 'email' => ['a@t.com', 'a@t.com', 's'] ]); /*prints error All of the required rules must pass for "Emails". - The Emails has a duplicate value. at row 1. - The Emails has a duplicate value. at row 2. - The Emails field must be a valid email. at row 3. */ $v->required() ->sometimes(function($value, $satisfier, $orig_field, $arrKey) { return $arrKey == 0; }) ->email()->sometimes() ->distinct()->sometimes() ->check('email|Emails', [ 'email' => ['a@t.com', 'b@t.com', 's@t.com'] ]); /*prints none, validation passes */ $v->assert();
包
致谢
灵感、代码片段等。