iulyanp/flex-validator 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

iulyanp/flex-validator

Composer 安装命令:

composer require iulyanp/flex-validator

包简介

A small validator based on Respect Validation library

README 文档

README

Latest Stable Version Total Downloads Latest Unstable Version License composer.lock available

A simple validator based on Respect Validation library, that provides an easy way to customize the error messages.

Installation

If you have composer installed globally you can run:

$ composer require iulyanp/flex-validator

or you can go with:

$ php composer.phar require iulyanp/flex-validator

Usage

FlexValidator can validate simple input:

$validator = new FlexValidator();
$validator->validate('Flex Validator', ['rules' => v::notBlank()->alnum('_')->noWhitespace()]);

if (!$validator->isValid()) {
    var_dump($validator->getErrors());
}

// do something with the valid data

For our little example the getErrors() will return something like this:

array:2 [
  "notBlank" => """ must not be blank"
  "alnum" => """ must contain only letters (a-z), digits (0-9) and "_""
]

But you can also validate arrays like this:

// use Respect Validator
use Respect\Validation\Validator;

$array = [
    'name' => 'Iulian Popa',
    'contact' => [
        'phone' => '07579940094',
        'address' => 'str, Ion Creanga nr.14 A bl. N2'
    ]
];

$rules = [
    'name' => Validator::notBlank(),
    'contact.phone' => Validator::notBlank()->numeric()->length(0, 10),
    'contact.address' => Validator::notBlank()->alnum('.')->length(6, 30),
];

$validator = new FlexValidator();
$validator->validate($array, $rules);

if (!$validator->isValid()) {
    var_dump($validator->getErrors());
}

The getErrors method will return an array with all breaking validation rules:

array:1 [
  "contact" => array:2 [
    "phone" => array:1 [
      "length" => ""07579940094" must have a length lower than 10"
    ]
    "address" => array:2 [
      "alnum" => ""str, Ion Creanga nr.14 A bl. N2" must contain only letters (a-z), digits (0-9) and ".""
      "length" => ""str, Ion Creanga nr.14 A bl. N2" must have a length between 6 and 30"
    ]
  ]
]

Validation methods

Currently you can validate simple values and multidimensional arrays.

$rules = [
    'rules' => Validator::notBlank(),
];

$validator->validate('value', $rules);

The validate method is a shortcut also for the array method which will validate multidimensional arrays.

$array = [
    'name' => 'Iulian Popa',
    'contact' => [
        'phone' => '07579940094',
        'address' => 'str, Ion Creanga nr.14 A bl. N2'
    ]
];

$rules = [
    'name' => Validator::notBlank(),
    'contact.phone' => Validator::notBlank()->numeric()->length(0, 10),
    'contact.address' => Validator::notBlank()->alnum('.')->length(6, 30),
];

$validator->array($array, $rules);

Disable named rules

As we saw in above the examples the error messages had the key of the errors array as the name of the broken rule: alnum, length.

array:1 [
  "contact" => array:2 [
    "address" => array:2 [
      "alnum" => ""str, Ion Creanga nr.14 A bl. N2" must contain only letters (a-z), digits (0-9) and ".""
      "length" => ""str, Ion Creanga nr.14 A bl. N2" must have a length between 6 and 30"
    ]
  ]
]

We can disable this with a simple call of the disableRulesName() method on the FlexValidator.

$validator->disableRulesName();

$validator->validate($array, $rules);

if (!$validator->isValid()) {
    var_dump($validator->getErrors());
}

//    array:1 [
//      "contact" => array:2 [
//        "phone" => array:1 [
//          0 => ""07579940094" must have a length lower than 10"
//        ]
//        "address" => array:2 [
//          0 => ""str, Ion Creanga nr.14 A bl. N2" must contain only letters (a-z), digits (0-9) and ".""
//          1 => ""str, Ion Creanga nr.14 A bl. N2" must have a length between 6 and 30"
//        ]
//      ]
//    ]

Use dot error keys

Also the errors array can be returned with dot keys.

$validator->useDotErrorKeys();
$validator->validate($array, $rules);

if (!$validator->isValid()) {
    var_dump($validator->getErrors());
}

//    array:2 [
//        "contact.phone" => array:1 [
//        "length" => ""07579940094" must have a length lower than 10"
//      ]
//      "contact.address" => array:2 [
//        "alnum" => ""str, Ion Creanga nr.14 A bl. N2" must contain only letters (a-z), digits (0-9) and ".""
//        "length" => ""str, Ion Creanga nr.14 A bl. N2" must have a length between 6 and 30"
//      ]
//    ]

You can also use the dot keys with disabled rule names together.

Error groups

Sometime when we validate an array of data maybe we want to wrap the error messages in a group. With FlexValidator we can do this in two ways: global group and specific group.

Specific group

First let's take a look on how we can specify a specific group on a specific array key.

use Respect\Validation\Validator;

$array = [
    'username' => '',
    'password' => '',
];
$rules = [
    'username' => [
        'rules' => Validator::notBlank(),
        'group' => 'login'
    ],
    'password' => [
        'rules' => Validator::notBlank(),
    ]
];

$validator = new FlexValidator();
$validator->validate($array, $rules);

// will return
array:2 [
  "login" => array:1 [
    "username" => array:1 [
      "notBlank" => "null must not be blank"
    ]
  ]
  "password" => array:1 [
    "notBlank" => "null must not be blank"
  ]
]

As you can see the field username was wrapped in a group login.

Global group

The global group will be applied only on the fields that don't have a specific group set. To specify a global group we can pass the third argument to the validate method.

use Respect\Validation\Validator;

$array = [
    'username' => '',
    'password' => '',
];
$rules = [
    'username' => [
        'rules' => Validator::notBlank(),
        'group' => 'login'
    ],
    'password' => [
        'rules' => Validator::notBlank(),
    ]
];

$validator = new FlexValidator();
$validator->validate($array, $rules, 'auth');

// will return
array:2 [
  "login" => array:1 [
    "username" => array:1 [
      "notBlank" => "null must not be blank"
    ]
  ]
  "auth" => array:1 [
    "password" => array:1 [
      "notBlank" => "null must not be blank"
    ]
  ]
]

Custom error messages

Almost all the time when we use a validation library we want to overwrite the default error messages. In the next steps we can see how FlexValidator made this objective very clean and easy to use.

Overwrite default error messages from RespectValidation

We can set the default error messages passing an array with the messages for each respect validation rule.

use Respect\Validation\Validator;

$array = [
    'name' => '',
];
$rules = [
    'name' => Validator::notBlank(),
];

$validator = new FlexValidator([
    'notBlank' => 'The value should not be blank'
]);
$validator->validate($array, $rules);

array:2 [
  "name" => array:1 [
    "notBlank" => "The value should not be blank"
  ]
]
Custom error messages globally for an entire set of data

We can go further and use custom error messages globally when we validate a set of data by passing the array with error messages as the fourth argument to the validate method.

use Respect\Validation\Validator;

$array = [
    'name' => '',
    'contact' => [
        'phone' => ''
    ]
];
$rules = [
    'name' => Validator::notBlank(),
    'contact.phone' => Validator::notBlank(),
];

$validator = new FlexValidator([
    'notBlank' => 'The value should not be blank'
]);
$validator->validate($array, $rules, '', [
    'notBlank' => 'The value should not be empty'
]);

// will return
array:2 [
  "name" => array:1 [
    "notBlank" => "The value should not be empty"
  ]
  "contact" => array:1 [
    "phone" => array:1 [
      "notBlank" => "The value should not be empty"
    ]
  ]
]
Custom error messages on specific value of an array

If we want to use a custom error message only for a specific field we can do so by specifying the messages key as an array with all the custom error messages. Here is an example.

use Respect\Validation\Validator;

$array = [
    'name' => '',
    'contact' => [
        'phone' => '',
        'address' => 'str, Ion Creanga nr.14 A bl. N2',
    ],
];

$rules = [
    'name' => Validator::notBlank(),
    'contact.phone' => [
        'rules' => Validator::notBlank()->numeric()->length(0, 10),
        'messages' => [
            'notBlank' => 'Please provide the phone number.',
            'numeric' => 'Your phone number shounld contain only numbers.',
            'length' => 'Your phone number should not be over 10 characters.'
        ],
    ],
];

$validator = new FlexValidator([
    'notBlank' => 'The value should not be blank'
]);
$validator->validate($array, $rules, '', [
    'notBlank' => 'The value should not be empty'
]);

// will return 
array:2 [
  "name" => array:1 [
    "notBlank" => "The value should not be empty"
  ]
  "contact" => array:1 [
    "phone" => array:2 [
      "notBlank" => "Please provide the phone number."
      "numeric" => "Your phone number shounld contain only numbers."
    ]
  ]
]

As you can see the error message from the name field is taken from the fourth argument of the validate method and the error messages for the phone number are taken from the messages array.

iulyanp/flex-validator 适用场景与选型建议

iulyanp/flex-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 416 次下载、GitHub Stars 达 1, 最近一次更新时间为 2018 年 01 月 24 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 416
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 11
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-01-24