werx/validation
Composer 安装命令:
composer require werx/validation
包简介
Validate individual data elements or group validation rules into sets to validate a form.
README 文档
README
Simple input validation.
Usage
There are two components to this library. A set of validation methods and an input validation engine.
Validators
The Validator class can be used to quickly validate a single piece of input.
include 'vendor/autoload.php'; use werx\Validation\Validator; $input = 'foo'; $valid = Validator::minlength($input, 4); var_dump($valid); /* bool(true) */
The following validators are available. Each validator returns a bool. true = passed validation, false = failed validation.
bool required (mixed $input) bool date (mixed $input [, $input_format = MM/DD/YYYY]) # Other input formats available YYYY/MM/DD, YYYY-MM-DD, YYYY/DD/MM, YYYY-DD-MM, DD-MM-YYYY, DD/MM/YYYY, MM-DD-YYYY, MM/DD/YYYY, YYYYMMDD, YYYYDDMM bool minlength(mixed $input, int $min) bool maxlength(mixed $input, int $max) bool exactlength(mixed $input, int $length) bool greaterthan($input, int $min) bool lessthan(mixed $input, int $max) bool alpha(mixed $input) bool alphanumeric(mixed $input) bool integer(mixed $input) bool float(mixed $input) bool numeric(mixed $input) bool email(mixed $input) bool url(mixed $input) bool phone(mixed $input) bool zipcode(mixed $input) bool startswith(mixed $input, string $match) bool endswith(mixed $input, string $match) bool contains(mixed $input, string $match) bool regex(mixed $input, string $regex) bool inlist(mixed $input, array $list)
Validation Engine
The Validation Engine is used to validate a set of data against a set of rules.
Usage
First, get an instance of the Validation Engine:
use werx\Validation\Engine as ValidationEngine; $validator = new ValidationEngine;
Then add rules:
$validator->addRule('firstname', 'First Name', 'required|minlength[2]|alpha');
Parameters
- Form input name / array key of the element you are validating
- User friendly label for the element
- Pipe-delimited list of rules
- Each rule corresponds to a method name from the Validator class
- If the method accepts arguments, the args should be in square brackets after the rule name
- Example:
minlength[2] - Exception: methods which accept an array as parameter should be in curly brackets after the rule name.
- Example:
inlist{red,white,blue}
- Example:
- Example:
- Except for the
requiredvalidator, all validators will return true if the input is empty.- In other words,
minlength[2]will only actually fire if you also add arequiredrule.
- In other words,
Now you can get a validation result.
$valid = $validator->validate($_POST);
Validating Input Arrays
Sometimes you aren't using a simple string as your input field name. Let's say your HTML input form is something like this:
<input type="text" name="volunteer[name]"> <input type="text" name="volunteer[email]">
To build a rule for in this scenario, separate the array name and key name with a period when adding your rule.
$validator->addRule('volunteer.name', 'Name', 'required|minlength[2]|alpha'); $validator->addRule('volunteer.email', 'Email Address', 'required|email');
Closures
In addition to predefined validation methods from the Validator class, you can also use closures to create custom validation methods.
$closure = function ($data, $id, $label) { $message = null; $success = $data[$id] == 'Foo'; if (!$success) { $message = sprintf('%s must equal "Foo"', $label); } return [$success, $message]; }; $validator->addRule('firstname', 'First Name', $closure); $valid = $validator->validate($_POST);
Three values will be passed to your closure:
- The full data set being validated.
- The id of the element being validated.
- The label for the element being validated.
The closure is expected to return an array.
- The first element of the array should be the validation result (
bool). - The second element of the array should be an error message to display if validation failed.
- If validation passed, message may be null.
Rulesets
What if you want to save groups of rules instead of adding each rule individually every time you want to validate them? We've got you covered.
Create a new class that extends werx\Validation\Ruleset and add your rules in the constructor.
namespace your\namespace\Rulesets; use werx\Validation\Ruleset; class Contact extends Ruleset { public function __construct() { $this->addRule('firstname', 'First Name', 'required|minlength[2]'); $this->addRule('lastname', 'Last Name', 'required'); $this->addRule('phone', 'Phone Number', 'required|phone'); $this->addRule('email', 'Email Address', 'required|email'); } }
Then when you are ready to validate this group of rules:
$contact_rules = new your\namespace\Rulesets\Contact; $validator->addRuleset($contact_rules); $valid = $validator->validate();
Utility Methods
There are a couple utilities to make dealing with validation results easier.
getErrorSummary()
Returns a simple array containing a list of validation error messages.
if (!$valid) { $summary = $validator->getErrorSummary(); } /* Array ( [0] => First Name must only contain the letters A-Z. [1] => First Name must be at least 2 characters long. [2] => Last Name is a required field. ) */
getErrorSummaryFormatted()
Returns the error summary formatted as an html unordered list (<ul>).
getErrorFields()
Returns list of fields that had an error. Useful if you want to apply some decoration to your form indicating which fields had a validation errors.
if (!$valid) { $error_fields = $validator->getErrorFields(); } /* Array ( [0] => firstname [1] => lastname ) */
getRequiredFields()
Once you've added your rules, you can get back a list of required fields. This is useful when you want to indicate on your form which fields must be completed.
$validator->addRule('firstname', 'First Name', 'required'); $validator->addRule('lastname', 'Last Name', 'required'); $validator->addRule('age', 'Age', 'required|integer'); $required = $validator->getRequiredFields(); /* Array ( [0] => firstname [1] => lastname [2] => age ) */
addCustomMessage()
Allows you to set custom error messages.
When displaying the error messages, {name} will be replaced with the name of the field being validated. The rest of the field
is parsed with sprintf() so that parameters like minlength can be placed in the returned error message.
Examples:
$validator->addCustomMessage('required', "You didn't provide a value for {name}!"); $validator->addCustomMessage('minlength', "Oops, {name} must be at least %d characters long.");
Installation
This package is installable and autoloadable via Composer as werx/validation. If you aren't familiar with the Composer Dependency Manager for PHP, you should read this first.
$ composer require werx/validation --prefer-dist
Contributing
Unit Testing
$ vendor/bin/phpunit
Coding Standards
This library uses PHP_CodeSniffer to ensure coding standards are followed.
I have adopted the PHP FIG PSR-2 Coding Standard EXCEPT for the tabs vs spaces for indentation rule. PSR-2 says 4 spaces. I use tabs. No discussion.
To support indenting with tabs, I've defined a custom PSR-2 ruleset that extends the standard PSR-2 ruleset used by PHP_CodeSniffer. You can find this ruleset in the root of this project at PSR2Tabs.xml
Executing the codesniffer command from the root of this project to run the sniffer using these custom rules.
$ ./codesniffer
werx/validation 适用场景与选型建议
werx/validation 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.13k 次下载、GitHub Stars 达 7, 最近一次更新时间为 2014 年 04 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「form」 「validator」 「validation」 「rules」 「validate」 「ruleset」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 werx/validation 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 werx/validation 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 werx/validation 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Runn Me! Validation and Sanitization Library
Extension for Opis JSON Schema
Diese Contao 4 Erweiterung stellt Google reCAPTCHA V2 in Form eines neuen Formularfeldes im Formulargenerator bereit. This extension provides Google reCAPTCHA V2 in the form of a new form field in the form generator of Contao Open Source CMS.
A Laravel Filament Forms slug field.
Adds request-parameter validation to the SLIM 3.x PHP framework
A jQuery augmented PHP library for creating and validating HTML forms
统计信息
- 总下载量: 6.13k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 8
- 点击次数: 16
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2014-04-25