PHP验证器类Validator
Particle\Validator是一个小巧优雅的实用的PHP验证类库,提供了一个非常简洁的API。它无需依赖其他组件,提供友好的文档,并且有利于扩展。
安装
composer require particle/validator
使用
在使用之前请确保在项目中引入了 vendor/autoload.php 文件
Code:
1. <?php
2. use Particle\Validator\Validator;
3. require './vendor/autoload.php';
4. $v = new Validator;
5. $v->required('first_name')->lengthBetween(2, 30)->alpha();
6. $v->required('last_name')->lengthBetween(2, 40)->alpha();
7. $data = [
8. 'first_name' => 'John',
9. 'last_name' => 'Doe',
10. ];
11. $result = $v->validate($data);
12. $result->isValid(); // 返回bool(true or false)
这个方法是内置的,主要用于检测某个key的值,如果希望检测的某个值可能为空,而希望验证通过,则我们可以设置该方法的第三个参数为true。(默认值为false 代表不能为空值)。其中 required 和 optional 的区别主要是如下 required 是验证的值必须存在;而 optional 是可选的,如果key存在,则验证,不存在,则不用验证。
数组方式验证
Code:
1. // 基本验证
2. $values = [
3. 'user' => [
4. 'username' => 'bob',
5. ]
6. ];
7. $v = new Validator;
8. $v->required('user.username')->alpha();
9. $result = $v->validate($values);
10. $result->getValues() === $values; // bool(true)
内置验证规则\
allowEmpty(callable $callback)是否可以为空值,true则通过 反之亦然
Code:
1. $v = new Validator;
2. // 如果用户名存在,则验证通过
3. $v->required('name')->allowEmpty(function (array $values) {
4. return $values['namePresent'] === true;
5. });
6. $v->validate(['namePresent' => true, 'name' => 'John'])->isValid(); // true
7. $v->validate(['namePresent' => true])->isValid(); // true
8. $v->validate(['namePresent' => false])->isValid(); // false
alnum($allowWhitespace = false) 包含数字和字母,不允许空格,(a-z, A-Z, 0-9)
alpha($allowWhitespace = false) 验证的字符包含 (a-z, A-Z),不允许空格。
between($min, $max) 验证必须在一个数值范围,如(12, 34)。
bool() 布尔Boolean值验证。
callback(callable $callable) 回调验证。
creditCard() 验证信用卡,验证之前必须先安装 composer require byrokrat/checkdigit。
datetime($format = null) 验证日期。
digits() 一串数字字符串验证,不包含小数。
each(callable $callable) 遍历验证。
email() 验证邮箱。
equals($value) 验证是否相等。
float()验证浮点数。
greaterThan($value) 大于某个值。
hash($hashAlgorithm, $allowUppercase = false) md5 sha1等验证。
inArray(array $array, $strict = true) 验证是否属于数组范围内
integer($strict = false) 整数验证。
isArray() 数组验证。
json()json格式字符串验证。
length($length) 长度验证。
lengthBetween($min, $max) 长度范围验证。
lessThan($value) 小于验证。
numeric() 验证浮点数和整数。
phone($countryCode) 验证手机号,使用之前先安装 composer require giggsey/libphonenumber-for-php。
regex($regex) 正则验证。
required(callable $callback) 必须存在,不能为空。
string() 字符串验证。
url($schemes = []) 验证URL。
uuid($version = Uuid::VALID_FORMAT) 验证UUID。
提示信息覆盖
Particle\Validator为默认规则提供了默认的消息提示,当然你也可以为验证规则设置特定的消息提示以覆盖默认值。
Code:
1. $v = new Validator;
2. $v->required('first_name')->lengthBetween(0, 5);
3. $v->required('last_name')->lengthBetween(0, 5);
4. $v->overwriteDefaultMessages([
5. LengthBetween::TOO_LONG => 'It\'s too long, that value'
6. ]);
7. $v->overwriteMessages([
8. 'first_name' => [
9. LengthBetween::TOO_LONG => 'First name is too long, mate'
10. ]
11. ]);
12. $result = $v->validate([
13. 'first_name' => 'this is too long',
14. 'last_name' => 'this is also too long',
15. ]);
16. var_dump($result->getMessages());
验证场景
验证库一般都可以根据场景来使用不同的验证,比如插入数据和更新数据的区别
Code:
1. $v = new Validator;
2. // 定义一个插入时候的验证规则
3. $v->context('insert', function(Validator $context) {
4. $context->required('first_name')->lengthBetween(2, 30);
5. });
6. // 定义一个更新时候的验证规则
7. $v->context('update', function(Validator $context) {
8. $context->optional('first_name')->lengthBetween(2, 30);
9. });
10. $v->validate([], 'update')->isValid(); // bool(true)
11. $v->validate([], 'insert')->isValid(); // bool(false), because first_name is required.
在MVC架构中使用验证器
很多时候,我们的项目都是进行分层开发的,例如常见的MVC,则我们可以在分层项目中调用该验证类,示例如下:
Code:
1. use Particle\Validator\ValidationResult;
2. use Particle\Validator\Validator;
3. class MyEntity
4. {
5. protected $id;
6. public function setId($id)
7. {
8. $this->id = $id;
9. return $this;
10. }
11. public function validate() {
12. $v = new Validator;
13. $v->required('id')->integer();
14. return new $v->validate($this->values());
15. }
16. protected function values()
17. {
18. return [
19. 'id' => $this->id,
20. ];
21. }
22. }
23. // in a controller:
24. $entity = new Entity();
25. $entity->setId($this->getParam('id'));
26. $result = $entity->validate();
27. if (!$result->isValid()) {
28. return $this->renderTemplate([
29. 'messages' => $result->getMessages() // or maybe even just pass in $result.
30. ]);
31. }
http://validator.particle-php.com/en/latest/
PHP验证器类Validator的更多相关文章
- [Swift]LeetCode591. 标签验证器 | Tag Validator
Given a string representing a code snippet, you need to implement a tag validator to parse the code ...
- 9、 Struts2验证(声明式验证、自定义验证器)
1. 什么是Struts2 验证器 一个健壮的 web 应用程序必须确保用户输入是合法.有效的. Struts2 的输入验证 基于 XWork Validation Framework 的声明式验证: ...
- vue-validator(vue验证器)
官方文档:http://vuejs.github.io/vue-validator/zh-cn/index.html github项目地址:https://github.com/vuejs/vue-v ...
- Hibernate验证器
第 4 章 Hibernate验证器 http://hibernate.org/validator/documentation/getting-started/#applying-constrain ...
- Flask系列09--Flask中WTForms插件,及自定义验证器
一.概述 django中的forms组件非常的方便,在flask中有WTForms的组件实现的也是类似的功能, 安装这个插件 二.简单使用 文档地址https://wtforms.readthedoc ...
- 自研后端HTTP请求参数验证器服务ParamertValidateService
好处:方便了后端对HTTP请求中参数进行核验,只需一次编写效验器,一行代码便可对所有参数的pojo进行参数核验!而且更改效验逻辑时只需要更改效验器类即可,实现了解耦合. 只需要程序员按照规范开发一个P ...
- 微软企业库5.0 学习之路——第五步、介绍EntLib.Validation模块信息、验证器的实现层级及内置的各种验证器的使用方法——下篇
一.独立验证器 我上篇中我将AndCompositeValidator和OrCompositeValidator归为独立验证器,这2个验证器主要是为了第一类验证服务,可以进行多种验证组合在一起进行复杂 ...
- struts2 基础4 验证器、 国际化
验证器: 验证器:用户输入验证 1.手动编程方式 )对于动作类中所有方法进行验证 a.动作类继承ActionSuport b.覆盖调用public void validate(){} 方法 c.在va ...
- Thinkphp5 模型 验证器执行顺序问题
Thinkphp5把模型的验证规则归为一个验证器,这种做法,不知到符不符合大家的心意,反正楼主是比较不爽的 楼主更倾向于tp3.2的验证规则直接写在模型里面,毕竟你的验证规则一般而言是针对模型来验证的 ...
随机推荐
- hdu 2485 Destroying the bus stations 最小费用最大流
题意: 最少需要几个点才能使得有向图中1->n的距离大于k. 分析: 删除某一点的以后,与它相连的所有边都不存在了,相当于点的容量为1.但是在网络流中我们只能直接限制边的容量.所以需要拆点来完成 ...
- CodeIgniter + smarty 实现widget功能
在开发过程中,经常需要widget功能,一可以隔离页面逻辑,二可以重用代码.结合smarty的plugin功能,可以方便的实现该功能. 譬如,我们的页面中可以这样写: {{extends file=' ...
- 循环语句 for循环、while循环、do while循环
循环语句可以在满足循环条件的情况下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则循环将一直执行下 ...
- Period UVA - 1328_结论题
Code: #include<cstdio> #include<cstring> using namespace std; const int maxn=1000000+5; ...
- js将timestamp对象与时间字符串之间的转换
1. 时间戳转日期字符串 var timestamp = timestampObj.time;获取时间戳的毫秒数 var d = new Date(timestamp); //根据时间戳生成的时间对象 ...
- iview关于menu结合router问题
#iview关于menu结合router问题 1. Menu.Item下router问题: 直接在Menu标签上绑定on-select事件,可以获取到name(name为元素绑定name) <M ...
- [poj 3666] Making the Grade (离散化 线性dp)
今天的第一题(/ω\)! Description A straight dirt road connects two fields on FJ's farm, but it changes eleva ...
- Linux 字符设备驱动简单总结(转)
http://my.oschina.net/u/1169027/blog/191538
- FreeMarker hello
一.什么是 FreeMarker FreeMarker 是一个用 Java 语言编写的模板引擎,它基于模板来生成文本输出.FreeMarker 与 Web 容器无关,即在 Web 运行时,它并不知道 ...
- robot Framework选择单选框