Valitron [1.3k] 数据验证
最后更新于:2022-04-02 02:24:08
[TOC]
> [github](https://github.com/vlucas/valitron)
## 安装
```
$ composer require vlucas/valitron
```
## 使用
### 简单使用
```
require __DIR__.'./../vendor/autoload.php';
use Valitron\Validator;
$validator = new Validator(['name' => '']);
$validator->rule('required', 'name');
if($validator->validate()) {
echo "Validation passed";
} else {
print_r($validator->errors());
//Array
//(
// [name] => Array
// (
// [0] => Name 不能为空
// )
//
//)
}
```
### 多验证规则
```
$rules = [
'required' => ['name', 'email'],
'alphaNum' => 'name',
'integer' => 'age',
'min' => [['age', 1]],
'email' => 'email'
];
$validator = new Validator(['name' => 'John Doe', 'age' => 34]);
$validator->rules($rules);
if ($validator->validate()) {
echo "Validation passed";
} else {
$errors = $validator->errors();
foreach ($errors as $arr) {
foreach ($arr as $error) {
echo $error . "\n";
}
};
}
````
### 验证日期
日期有四个验证规则:`date`,`dateFormat`,`dateBefore`和`dateAfter`。
```
$validator = new Validator(['created_at' => '2019-03-01']);
$validator->rule('dateBefore', 'created_at', '2018-10-13');
```
### 验证ip
```
$vals = ['ip1' => '127.0.0.1',
'ip2' => 'FE80:0000:0000:0000:0202:B3FF:FE1E:8329',
'ip3' => 'FE80::0202:B3FF:FE1E:8329',
'ip4' => '0.0.1'];
$rules = [
'ip' => ['ip1', 'ip2', 'ip3', 'ip4'],
];
$validator = new Validator($vals);
$validator->rules($rules);
if ($validator->validate()) {
echo "Validation passed";
} else {
print_r($validator->errors());
//Array
//(
// [ip4] => Array
// (
// [0] => Ip4 is not a valid IP address
// )
//
//)
}
```
### 自定义消息
```
$validator = new Validator(['name' => '']);
$validator->rule('required', 'name')
->message('{field} 不为空')
->label("姓名");
```
### 值的验证子集
方式一:
```
$vals = ['colors' => ['green', 'blue', 'black']];
$validator = new Validator($vals);
$validator->rule('subset', 'colors', ['red', 'green', 'blue', 'orange', 'yellow']);
```
方式二:
```
Validator::lang('zh-cn');
$v = new Valitron\Validator(
['settings' => [
['threshold' => 50],
['threshold' => 90]
]]);
$v->rule('max', 'settings.*.threshold', 10);
if($v->validate()){
echo "Yay! We're all good!";
}else{
print_r($v->errors());
//Array
//(
// [settings.*.threshold] => Array
// (
// [0] => Settings.*.threshold 必须小于 10
// )
//
//)
}
```
方式三:
```
$v = new Valitron\Validator(array('values' => array(50, 90)));
$v->rule('max', 'values.*', 100);
if($v->validate()) {
echo "Yay! We're all good!";
} else {
// Errors
print_r($v->errors());
}
```
方式四:
```
$v = new Valitron\Validator(array('user' => array('first_name' => 'Steve', 'last_name' => 'Smith', 'username' => 'Batman123')));
$v->rule('alpha', 'user.first_name')->rule('alpha', 'user.last_name')->rule('alphaNum', 'user.username');
if($v->validate()) {
echo "Yay! We're all good!";
} else {
// Errors
print_r($v->errors());
}
```
### 必填可以为空
```
$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin', 'required_but_null' => null]);
$v->rules([
'required' => [
['username'],
['password'],
['required_but_null', true] // boolean flag allows empty value so long as the field name is set on the data array
]
]);
$v->validate();
```
### 自定义语言路径
```
V::langDir(__DIR__.'/validator_lang'); // always set langDir before lang.
V::lang('ar');
```
### 验证规则
```
required - Field is required
requiredWith - Field is required if any other fields are present
requiredWithout - Field is required if any other fields are NOT present
equals - Field must match another field (email/password confirmation)
different - Field must be different than another field
accepted - Checkbox or Radio must be accepted (yes, on, 1, true)
numeric - Must be numeric
integer - Must be integer number
boolean - Must be boolean
array - Must be array
length - String must be certain length
lengthBetween - String must be between given lengths
lengthMin - String must be greater than given length
lengthMax - String must be less than given length
min - Minimum
max - Maximum
listContains - Performs in_array check on given array values (the other way round than in)
in - Performs in_array check on given array values
notIn - Negation of in rule (not in array of values)
ip - Valid IP address
ipv4 - Valid IP v4 address
ipv6 - Valid IP v6 address
email - Valid email address
emailDNS - Valid email address with active DNS record
url - Valid URL
urlActive - Valid URL with active DNS record
alpha - Alphabetic characters only
alphaNum - Alphabetic and numeric characters only
ascii - ASCII characters only
slug - URL slug characters (a-z, 0-9, -, _)
regex - Field matches given regex pattern
date - Field is a valid date
dateFormat - Field is a valid date in the given format
dateBefore - Field is a valid date and is before the given date
dateAfter - Field is a valid date and is after the given date
contains - Field is a string and contains the given string
subset - Field is an array or a scalar and all elements are contained in the given array
containsUnique - Field is an array and contains unique values
creditCard - Field is a valid credit card number
instanceOf - Field contains an instance of the given class
optional - Value does not need to be included in data array. If it is however, it must pass validation.
arrayHasKeys - Field is an array and contains all specified keys.
```
';