shippeo/valitron
Composer 安装命令:
composer require shippeo/valitron
包简介
Simple, elegant, stand-alone validation library with NO dependencies
关键字:
README 文档
README
Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron uses simple, straightforward validation methods with a focus on readable and concise syntax. Valitron is the simple and pragmatic validation library you've been looking for.
Why Valitron?
Valitron was created out of frustration with other validation libraries that have dependencies on large components from other frameworks like Symfony's HttpFoundation, pulling in a ton of extra files that aren't really needed for basic validation. It also has purposefully simple syntax used to run all validations in one call instead of individually validating each value by instantiating new classes and validating values one at a time like some other validation libraries require.
In short, Valitron is everything you've been looking for in a validation library but haven't been able to find until now: simple pragmatic syntax, lightweight code that makes sense, extensible for custom callbacks and validations, well tested, and without dependencies. Let's get started.
Installation
Valitron uses Composer to install and update:
curl -s http://getcomposer.org/installer | php
php composer.phar require vlucas/valitron
The examples below use PHP 5.4 syntax, but Valitron works on PHP 5.3+.
Usage
Usage is simple and straightforward. Just supply an array of data you
wish to validate, add some rules, and then call validate(). If there
are any errors, you can call errors() to get them.
$v = new Valitron\Validator(array('name' => 'Chester Tester')); $v->rule('required', 'name'); if($v->validate()) { echo "Yay! We're all good!"; } else { // Errors print_r($v->errors()); }
Using this format, you can validate $_POST data directly and easily,
and can even apply a rule like required to an array of fields:
$v = new Valitron\Validator($_POST); $v->rule('required', ['name', 'email']); $v->rule('email', 'email'); if($v->validate()) { echo "Yay! We're all good!"; } else { // Errors print_r($v->errors()); }
You may use dot syntax to access members of multi-dimensional arrays, and an asterisk to validate each member of an array:
$v = new Valitron\Validator(array('settings' => array( array('threshold' => 50), array('threshold' => 90) ))); $v->rule('max', 'settings.*.threshold', 100); if($v->validate()) { echo "Yay! We're all good!"; } else { // Errors print_r($v->errors()); }
Setting language and language dir globally:
// boot or config file use Valitron\Validator as V; V::langDir(__DIR__.'/validator_lang'); // always set langDir before lang. V::lang('ar');
Built-in Validation Rules
required- Required fieldequals- Field must match another field (email/password confirmation)different- Field must be different than another fieldaccepted- Checkbox or Radio must be accepted (yes, on, 1, true)numeric- Must be numericinteger- Must be integer numberarray- Must be arraylength- String must be certain lengthlengthBetween- String must be between given lengthslengthMin- String must be greater than given lengthlengthMax- String must be less than given lengthmin- Minimummax- Maximumin- Performs in_array check on given array valuesnotIn- Negation ofinrule (not in array of values)ip- Valid IP addressemail- Valid email addressurl- Valid URLurlActive- Valid URL with active DNS recordalpha- Alphabetic characters onlyalphaNum- Alphabetic and numeric characters onlyslug- URL slug characters (a-z, 0-9, -, _)regex- Field matches given regex patterndate- Field is a valid datedateFormat- Field is a valid date in the given formatdateBefore- Field is a valid date and is before the given datedateAfter- Field is a valid date and is after the given datecontains- Field is a string and contains the given stringcreditCard- Field is a valid credit card numberinstanceOf- Field contains an instance of the given classoptional- Value does not need to be included in data array. If it is however, it must pass validation.
NOTE: If you are comparing floating-point numbers with min/max validators, you should install the BCMath extension for greater accuracy and reliability. The extension is not required for Valitron to work, but Valitron will use it if available, and it is highly recommended.
Credit Card Validation usage
Credit card validation currently allows you to validate a Visa visa,
Mastercard mastercard, Dinersclub dinersclub, American Express amex
or Discover discover
This will check the credit card against each card type
$v->rule('creditCard', 'credit_card');
To optionally filter card types, add the slug to an array as the next parameter:
$v->rule('creditCard', 'credit_card', ['visa', 'mastercard']);
If you only want to validate one type of card, put it as a string:
$v->rule('creditCard', 'credit_card', 'visa');
If the card type information is coming from the client, you might also want to still specify an array of valid card types:
$cardType = 'amex'; $v->rule('creditCard', 'credit_card', $cardType, ['visa', 'mastercard']); $v->validate(); // false
Adding Custom Validation Rules
To add your own validation rule, use the addRule method with a rule
name, a custom callback or closure, and a error message to display in
case of an error. The callback provided should return boolean true or
false.
Valitron\Validator::addRule('alwaysFail', function($field, $value, array $params, array $fields) { return false; }, 'Everything you do is wrong. You fail.');
Alternate syntax for adding rules
As the number of rules grows, you may prefer the alternate syntax for defining multiple rules at once.
$rules = [ 'required' => 'foo', 'accepted' => 'bar', 'integer' => 'bar' ]; $v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 1)); $v->rules($rules); $v->validate();
If your rule requires multiple parameters or a single parameter more complex than a string, you need to wrap the rule in an array.
$rules = [ 'required' => [ ['foo'], ['bar'] ], 'length' => [ ['foo', 3] ] ];
You can also specify multiple rules for each rule type.
$rules = [ 'length' => [ ['foo', 5], ['bar', 5] ] ];
Putting these techniques together, you can create a complete rule definition in a relatively compact data structure.
You can continue to add individual rules with the rule method
even after specifying a rule definition via an array. This is
especially useful if you are defining custom validation rules.
$rules = [ 'required' => 'foo', 'accepted' => 'bar', 'integer' => 'bar' ]; $v = new Valitron\Validator(array('foo' => 'bar', 'bar' => 1)); $v->rules($rules); $v->rule('min', 'bar', 0); $v->validate();
Adding field label to messages
You can do this in two different ways, you can add a individual label to a rule or an array of all labels for the rules.
To add individual label to rule you simply add the label method after the rule.
$v = new Valitron\Validator(array()); $v->rule('required', 'name')->message('{field} is required')->label('Name'); $v->validate();
There is a edge case to this method, you wouldn't be able to use a array of field names in the rule definition, so one rule per field. So this wouldn't work:
$v = new Valitron\Validator(array()); $v->rule('required', array('name', 'email'))->message('{field} is required')->label('Name'); $v->validate();
However we can use a array of labels to solve this issue by simply adding the labels method instead:
$v = new Valitron\Validator(array()); $v->rule('required', array('name', 'email'))->message('{field} is required'); $v->labels(array( 'name' => 'Name', 'email' => 'Email address' )); $v->validate();
This introduces a new set of tags to your error language file which looks like {field}, if you are using a rule like equals you can access the second value in the language file by incrementing the field with a value like {field1}.
Running Tests
The test suite depends on the Composer autoloader to load and run the Valitron files. Please ensure you have downloaded and installed Composer before running the tests:
- Download Composer
curl -s http://getcomposer.org/installer | php - Run 'install'
php composer.phar install - Run the tests
phpunit
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Make your changes
- Run the tests, adding new ones for your own code if necessary (
phpunit) - Commit your changes (
git commit -am 'Added some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request
- Pat yourself on the back for being so awesome
shippeo/valitron 适用场景与选型建议
shippeo/valitron 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.91k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2016 年 03 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「validator」 「validation」 「valid」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 shippeo/valitron 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 shippeo/valitron 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 shippeo/valitron 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Cascade attribute for Symfony Validator, reimplementing the Valid constraint in a more flexible and understandable way
Runn Me! Validation and Sanitization Library
Extension for Opis JSON Schema
Simple minimal but useful set of utils (properties, strings, datetimes, etc.)
Adds request-parameter validation to the SLIM 3.x PHP framework
A jQuery augmented PHP library for creating and validating HTML forms
统计信息
- 总下载量: 8.91k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: BSD
- 更新时间: 2016-03-25