承接 popphp/pop-validator 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

popphp/pop-validator

Composer 安装命令:

composer require popphp/pop-validator

包简介

Pop Validator Component for Pop PHP Framework

README 文档

README

Build Status Coverage Status

Join the chat at https://discord.gg/TZjgT74U7E

Overview

pop-validator is a component for validating values and returning the appropriate result messaging. The component comes with a set of built-in evaluation objects and also the ability to extend the component and build your own.

pop-validator is a component of the Pop PHP Framework.

Top

Install

Install pop-validator using Composer.

composer require popphp/pop-validator

Or, require it in your composer.json file

"require": {
    "popphp/pop-validator" : "^4.6.5"
}

Top

Quickstart

Here's a list of the available built-in validators, all under the namespace Pop\Validator\:

Built-in Validators
Accepted GreaterThan IsJson
AlphaNumeric HasAtLeast IsNotEmpty
Alpha HasAtMost IsNotNull
BetweenInclude HasCountEqual IsNull
Between HasCountGreaterThan IsSubnetOf
Boolean HasCountGreaterThanEqual LengthBetweenInclude
Contains HasCountLessThan LengthBetween
CountEqual HasCountLessThanEqual LengthGreaterThanEqual
CountGreaterThanEqual HasCountNotEqual LengthGreaterThan
CountGreaterThan HasOne LengthLessThanEqual
CountLessThanEqual HasOneGreaterThan LengthLessThan
CountLessThan HasOneGreaterThanEqual Length
CountNotEqual HasOneLessThan LessThanEqual
CreditCard HasOneLessThanEqual LessThan
DateTimeBetweenInclude HasOneThatEquals NotContains
DateTimeBetween HasOnlyOne NotEmpty
DateTimeEqual HasOnlyOneGreaterThan NotEndsWith
DateTimeGreaterThanEqual HasOnlyOneGreaterThanEqual NotEqual
DateTimeGreaterThan HasOnlyOneLessThan NotInArray
DateTimeLessThanEqual HasOnlyOneLessThanEqual NotIn
DateTimeLessThan HasOnlyOneThatEquals NotStartsWith
DateTimeNotEqual InArray Numeric
Declined In RegEx
Email Ipv4 Required
EndsWith Ipv6 StartsWith
Equal IsArray Subnet
GreaterThanEqual IsEmpty Url

Check an email value

$validator = new Pop\Validator\Email();

// Returns false
if ($validator->evaluate('bad-email-address')) {
    // Prints out the default message 'The value must be a valid email format.'
    echo $validator->getMessage();
}

// Returns true
if ($validator->evaluate('good@email.com')) {
    // Do something with a valid email address.
}

Validate against a specific value

$validator = new Pop\Validator\LessThan(10);

if ($validator->evaluate(8)) { } // Returns true

Set a custom message

$validator = new Pop\Validator\RegEx(
    '/^.*\.(jpg|jpeg|png|gif)$/i',
    'You must only submit JPG, PNG or GIF images.'
);

// Returns false
if ($validator->evaluate('image.bad')) {
    echo $validator->getMessage();
}

Alternatively:

$validator = new Pop\Validator\RegEx('/^.*\.(jpg|jpeg|png|gif)$/i');
$validator->setMessage('You must only submit JPG, PNG or GIF images.');

if ($validator->evaluate('image.jpg')) { } // Returns true

Top

Validation Sets

Validation sets are a way to group validators together to evaluate all of them at one time. With that, a level of strictness can be set to enforce whether or not all the validations have to pass or just some of them.

use Pop\Validator\ValidatorSet;

$set = new ValidatorSet();
$set->addValidators(['username' => 'AlphaNumeric']);

if ($set->evaluate(['username' => 'username_123'])) {
    echo 'The username satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Multiple Validators

use Pop\Validator\ValidatorSet;

$set = new ValidatorSet();
$set->addValidators(['username' => ['AlphaNumeric' => null, 'LengthGte' => 8]]);

if ($set->evaluate(['username' => 'username_123'])) {
    echo 'The username satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Custom Messaging

use Pop\Validator\ValidatorSet;

$set = new ValidatorSet();
$set->addValidators([
    'username' => [
        'AlphaNumeric' => [
            'value'   => null,
            'message' => 'The username can only contain alphanumeric characters.'
        ],
        'LengthGte' => 8
    ]
]);

if ($set->evaluate(['username' => 'username_123'])) {
    echo 'The username satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Lazy-Loading vs Eager-Loading

If the validators are added to the set validator using the add* methods will store the validator configuration and not create the validator objects until the validator set is evaluated (lazy-loading.) Using the load* methods, actual validator objects will be stored in the instance of the validator set object (eager-loading.)

Strictness

The strictness of the validator set can be set as needed. If set to STRICT_NONE then only one validator in the set would have to pass in order for the whole set to pass. The same applies for conditions as well:

use Pop\Validator\ValidatorSet;

$set = ValidatorSet();
$set->addValidators(['username' => ['AlphaNumeric' => null, 'LengthGte' => 8]]);
$set->setStrict(ValidatorSet::STRICT_NONE);

if ($set->evaluate(['username' => 'someuser_!23'])) {
    echo 'The username satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Available strict constants are:

  • STRICT_NONE
  • STRICT_VALIDATIONS_ONLY
  • STRICT_CONDITIONS_ONLY
  • STRICT_BOTH (default)

Top

Conditions

Conditions can be added to a validation set that would need to pass in order for the validations to evaluate. Conditions are validators themselves. And the strictness level can be utilized as well to enforce whether or not all the conditions pass or just some of them.

Note: By default, conditions store their validation configuration via lazy-loading and do not create the validator object until the condition is evaluated.

use Pop\Validator\ValidatorSet;
use Pop\Validator\Condition;

$set = new ValidatorSet();
$set->addCondition(new Condition('client_id', 'Equal', '1'));
$set->addValidator('documents', 'NotEmpty');

$data = [
    'client_id' => 1,
    'documents' => [
        'some_file_1.pdf',
        'some_file_2.pdf',
    ]
];

if ($set->evaluate($data)) {
    echo 'The client order data satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

In the above example, if the value of client_id is changed to 2, the validators will not be evaluated, as the required conditions would not be satisfied.

Top

Rules

Rules provide a shorthand way to wire up validations and conditions within the validation set. Rules are colon-separated strings compromised of a field, a validator and optional value and message values. The validator should be a snake_case format of the class string, e.g. HasOne class should be written as has_one.

Below is the same example from above, but using rules instead:

$set = Pop\Validator\ValidatorSet::createFromRules([
    'username:alpha_numeric',
    'username:length_gte:8'
]);

if ($set->evaluate(['username' => 'someuser_123'])) {
    echo 'The username satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Conditions can be added using rules as well. Here is the example from above using rules instead:

use Pop\Validator\ValidatorSet;

$set = ValidatorSet::createFromRules('documents:not_empty')
    ->addConditionFromRule('client_id:equal:1');

$data = [
    'client_id' => 1,
    'documents' => [
        'some_file_1.pdf',
        'some_file_2.pdf',
    ]
];

if ($set->evaluate($data)) {
    echo 'The client order data satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Rule Messages

Custom messaging can be passed via the rule format as well, in the 4th position:

$set = Pop\Validator\ValidatorSet::createFromRules([
    'username:length_gt:8:The username must be greater than 8 characters.'
]);

Referencing Fields

When writing rules, fields passed into the input data at the time of evaluating the data can be accessed by using brackets:

use Pop\Validator\ValidatorSet;

$set = ValidatorSet::createFromRules('value_1:equal:[value_2]');

$data = [
    'value_1' => 'test',
    'value_2' => 'test'
];

if ($set->evaluate($data)) {
    echo 'The data satisfies the requirements.' . PHP_EOL;
} else {
    print_r($set->getErrors());
}

Top

popphp/pop-validator 适用场景与选型建议

popphp/pop-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 20.19k 次下载、GitHub Stars 达 5, 最近一次更新时间为 2014 年 12 月 08 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「validator」 「validation」 「pop」 「pop php」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 popphp/pop-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 popphp/pop-validator 我们能提供哪些服务?
定制开发 / 二次开发

基于 popphp/pop-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 20.19k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 5
  • 点击次数: 13
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 2014-12-08