chmielewskitomasz / validator
简单验证工具,允许您验证简单和嵌套结构,引入了条件字段。所有需要的功能都在这里。非常适合REST端点验证。无需任何依赖。
1.2.7
2018-07-17 11:57 UTC
Requires
- php: ^7.1
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.8
- phpspec/phpspec: ^4.3
- phpstan/phpstan: ^0.9.2
- phpunit/phpunit: ^6.0.8 || ^5.7.15
- squizlabs/php_codesniffer: ^2.8.1
README
如何安装它?
composer require chmielewskitomasz/validator
如何使用它?
require_once __FILE__ . '/vendor/autoload.php'; use Hop\Strategy\Strategy; use Hop\Strategy\Field; use Hop\StdValidator; // first, create your input validation strategy class AlbumInputValidator implements Strategy { /** * @inheritdoc */ public function getFields(): array { $nameField = new Field( 'name', true, null ); $phoneField = new Field( 'phone' false, null ); $phoneField->registerValidator('Digits'); $phoneField->registerValidator('Length', ['min' => 9, 'max' => 9]); return [ $nameField, $phoneField ]; } } // second, create stdValidator $validator = StdValidator::fromConfig(include __DIR__ . '/config/validators.php'); // three - validate your input $myInput = [ 'name' => 'Tom', 'phone' => '999888000' ]; $validator->isValid($myInput, new AlbumInputValidator()); // true $validator->getMessages($myInput, new AlbumInputValidator()); // null $myWrongInput = [ 'name' => 'Tom', 'phone' => 'thisShouldBeA9DigitsNumber' ]; $validator->isValid($myWrongInput, new AlbumInputValidator()) // false $validator->getMessages($myWrongInput, new AlbumInputValidato()) // ['phone' => Message()]
好吧,我想我的字段是可选的,但如果它被传递,我想验证它
// In strategy: // ... public function getFields(): array { $field = new Field( 'phone', false, // set second parameter 'required' as false, null ); $field->registerValidator('Digits', null); return [$field]; } // ... // and then $validator->isValid([], new AlbumInputValidator()); // true $validator->isValid(['phone' => 'abcdefg'], new AlbumInputValidator()); // false
我想一个字段是条件性的。我的意思是,如果例如街道名称没有传递,我不希望门牌号是必需的。
看看这里
// In strategy: // ... public function getFields(): array { $streetField = new Field( 'street', false, null ); $houseNumberField = new Field( 'houseNumber', true, function (array $inputData) { return !isset($inputData['street']); } ); return [$streetField, $houseNumberField]; } // ... // and then $validator->isValid(['street' => 'High st.'], new AlbumInputValidator()); // false $validator->isValid([], new AlbumInputValidator()); // true $validator->isValid(['street' => 'High st.', 'houseNumber' => '12'], new AlbumInputValidator()); // true
我如何实现自己的验证器?
很简单。你可以帮助我为此项目做出贡献。或者,如果你不想,只需创建一个实现 Hop\Validator\Strategy\Strategy
的类,并将其作为数组传递给 StdValidator::fromConfig()
,例如
$myValidators = [ 'MyValidator' => 'Path\To\Validator\Class' ]; $validator = StdValidator::fromConfig( \array_merge(include __DIR__ . '/config/validators.php', $myValidators) );
© Chmielewski Tomasz