alexgarrett/violin
最新稳定版本:2.2.2
Composer 安装命令:
composer require alexgarrett/violin
包简介
Violin is an easy to use, highly customisable PHP validator.
关键字:
README 文档
README
Violin is an easy to use, highly customisable PHP validator.
Note: This package is under heavy development and is not recommended for production.
Installing
Install using Composer.
{
"require": {
"alexgarrett/violin": "2.*"
}
}
Basic usage
use Violin\Violin; $v = new Violin; $v->validate([ 'name' => ['billy', 'required'], 'age' => [20, 'required|int'] ]); if($v->passes()) { echo 'Validation passed, woo!'; } else { echo '<pre>', var_dump($v->errors()->all()), '</pre>'; }
Adding custom rules
Adding custom rules is simple. If the closure returns false, the rule fails.
$v->addRuleMessage('isbanana', 'The {field} field expects "banana", found "{value}" instead.'); $v->addRule('isbanana', function($value, $input, $args) { return $value === 'banana'; }); $v->validate([ 'fruit' => ['apple', 'isbanana'] ]);
Adding custom error messages
You can add rule messages, or field messages for total flexibility.
Adding a rule message
$v->addRuleMessage('required', 'You better fill in the {field} field, or else.');
Adding rule messages in bulk
$v->addRuleMessages([ 'required' => 'You better fill in the {field} field, or else.', 'int' => 'The {field} needs to be an integer, but I found {value}.', ]);
Adding a field message
Any field messages you add are used before any default or custom rule messages.
$v->addFieldMessage('username', 'required', 'You need to enter a username to sign up.');
Adding field messages in bulk
$v->addFieldMessages([ 'username' => [ 'required' => 'You need to enter a username to sign up.' ], 'age' => [ 'required' => 'I need your age.', 'int' => 'Your age needs to be an integer.', ] ]);
Using Field Aliases
Field Aliases helps you format any error messages without showing weird form names or the need to create a custom error.
$v->validate([ 'username_box|Username' => ['' => 'required'] ]); // Error output: "Username is required."
Callbacks
Violin allows you to attach callbacks to be run before or after any validation. This might be useful if you need to do some further validation, or maybe raise an event. You can add as many before and after callbacks as you want, and you can also use the current Violin instance within them.
Examples:
$v->before(function($violin) { // This will happen before the validation.. });
$v->after(function($violin) { // This will happen after the validation.. });
Extending Violin
You can extend the Violin class to add custom rules, rule messages and field messages. This way, you can keep a tidy class to handle custom validation if you have any dependencies, like a database connection or language files.
class MyValidator extends Violin { protected $db; public function __construct(PDO $db) { $this->db = $db; // Add rule message for custom rule method. $this->addRuleMessage('uniqueUsername', 'That username is taken.'); } // Custom rule method for checking a unique username in our database. // Just prepend custom rules with validate_ public function validate_uniqueUsername($value, $input, $args) { $user = $this->db->prepare(" SELECT count(*) as count FROM users WHERE username = :username "); $user->execute(['username' => $value]); if($user->fetchObject()->count) { return false; // Username exists, so return false. } return true; } } // A database connection. $db = new PDO('mysql:host=127.0.0.1;dbname=website', 'root', 'root'); // Instantiate your custom class with dependencies. $v = new MyValidator($db); $v->validate([ 'username' => ['billy', 'required|uniqueUsername'] ]);
Rules
This list of rules are in progress. Of course, you can always contribute to the project if you'd like to add more to the base ruleset.
alnum
If the value is alphanumeric.
alnumDash
If the value is alphanumeric. Dashes and underscores are permitted.
alpha
If the value is alphabetic letters only.
array
If the value is an array.
between(int, int)
Checks if the value is within the intervals defined. This check is inclusive, so 5 is between 5 and 10.
bool
If the value is a boolean.
If the value is a valid email.
int
If the value is an integer, including numbers within strings. 1 and '1' are both classed as integers.
number
If the value is a number, including numbers within strings.
Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.
ip
If the value is a valid IP address.
min(int, [number])
Check if string length is greater than or equal to given int. To check the size of a number, pass the optional number option.
$v->validate([ 'username' => ['billy', 'required|min(3)|max(20)'], 'age' => ['20', 'required|min(18, number)|max(100, number)'] ]);
max(int, [number])
Check if string length is less than or equal to given int. To check the size of a number, pass the optional number option.
required
If the value is present.
url
If the value is formatted as a valid URL.
matches(field)
Checks if one given input matches the other. For example, checking if password matches password_confirm.
date
If the given input is a valid date.
You can validate human readable dates like '25th October 1961' and instances of DateTime. For example:
$twoDaysAgo = new DateTime('2 days ago'); $date = $twoDaysAgo->format('d M Y'); $v->validate([ 'date' => [$date, 'required|date'] ]);
checked
If a field has been 'checked' or not, meaning it contains one of the following values: 'yes', 'on', '1', 1, true, or 'true'. This can be used for determining if an HTML checkbox has been checked.
regex(expression)
If the given input has a match for the regular expression given.
Contributing
Please file issues under GitHub, or submit a pull request if you'd like to directly contribute.
Running tests
Tests are run with phpunit. Run ./vendor/bin/phpunit to run tests.
alexgarrett/violin 适用场景与选型建议
alexgarrett/violin 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 65.62k 次下载、GitHub Stars 达 206, 最近一次更新时间为 2015 年 01 月 12 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「validation」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 alexgarrett/violin 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 alexgarrett/violin 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 alexgarrett/violin 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Adds request-parameter validation to the SLIM 3.x PHP framework
A jQuery augmented PHP library for creating and validating HTML forms
A Laravel validator for delimiter-separated list of emails.
A CakePHP behavior to validate foreign keys
PHP Validator for stuff.
Stand-alone PHP Class for Data Sanitization and Validation
统计信息
- 总下载量: 65.62k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 213
- 点击次数: 14
- 依赖项目数: 4
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-01-12