原文: https://zetcode.com/php/valitron/

PHP Valitron 教程展示了如何使用 Valitron 验证包验证 PHP 值。

Valitron

Valitron 是一个简单,最小且优雅的独立验证库,没有依赖项。

安装

  1. $ composer require vlucas/valitron
  2. $ composer require tightenco/collect

我们安装了 Valitron 套件和 Laravel 的集合套件。

简单的例子

在第一个示例中,我们展示了如何进行非常简单的验证。

simple.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $validator = new Validator(['name' => 'John Doe']);
  5. $validator->rule('required', 'name');
  6. if($validator->validate()) {
  7. echo "Validation passed";
  8. } else {
  9. $coll = collect($validator->errors());
  10. $messages = $coll->flatten();
  11. foreach ($messages as $message) {
  12. echo $message . "\n";
  13. }
  14. }

该示例验证一个必需值。

  1. use Valitron\Validator;

我们包括验证器。

  1. $validator = new Validator(['name' => 'John Doe']);

我们创建Validator的实例,并将其传递给要验证的值。

  1. $validator->rule('required', 'name');

我们用rule()方法指定required规则。

  1. if($validator->validate()) {

验证通过validate()执行。

  1. $coll = collect($validator->errors());
  2. $messages = $coll->flatten();
  3. foreach ($messages as $message) {
  4. echo $message . "\n";
  5. }

如果验证失败,我们将得到错误并显示。

  1. $ php simple.php
  2. Validation passed

这是输出。

验证规则

Valitron 包含一组预定义规则,例如requiredemailminmaxurl

规则可以与|字符结合使用。

multiple_rules.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $rules = [
  5. 'required' => ['name', 'email'],
  6. 'alphaNum' => 'name',
  7. 'integer' => 'age',
  8. 'min' => [['age', 1]],
  9. 'email' => 'email'
  10. ];
  11. $validator = new Validator(['name' => 'John Doe', 'age' => 34]);
  12. $validator->rules($rules);
  13. if ($validator->validate()) {
  14. echo "Validation passed";
  15. } else {
  16. $errors = $validator->errors();
  17. foreach ($errors as $arr) {
  18. foreach ($arr as $error) {
  19. echo $error . "\n";
  20. }
  21. };
  22. }

该示例使用了多个验证规则。

  1. $rules = [
  2. 'required' => ['name', 'email'],
  3. 'alphaNum' => 'name',
  4. 'integer' => 'age',
  5. 'min' => [['age', 1]],
  6. 'email' => 'email'
  7. ];

我们有四个验证规则。 需要nameemailname必须为字母数字值,age必须为整数,最小值为 1。最后,email必须为有效的电子邮件地址。

  1. $ php multiple_rules.php
  2. Email is required
  3. Email is not a valid email address
  4. Name must contain only letters a-z and/or numbers 0-9

该示例以三个验证失败结束。

Valitron 链接规则

可以通过链接rule()方法来添加规则。

chaining.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $validator = new Validator(['name' => 'John Doe', 'email' => 'johndoe#gmail.com']);
  5. $validator->rule('required', 'name')->rule('email', 'email');
  6. if($validator->validate()) {
  7. echo "Validation passed";
  8. } else {
  9. $coll = collect($validator->errors());
  10. $messages = $coll->flatten();
  11. foreach ($messages as $message) {
  12. echo $message . "\n";
  13. }
  14. }

该示例链接了两个规则。

  1. $validator->rule('required', 'name')->rule('email', 'email');

我们通过链接rule()方法添加了两个验证规则。

验证日期

日期有四个验证规则:datedateFormatdateBeforedateAfter

date_before.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $validator = new Validator(['created_at' => '2019-03-01']);
  5. $validator->rule('dateBefore', 'created_at', '2018-10-13');
  6. if ($validator->validate()) {
  7. echo "Validation passed";
  8. } else {
  9. $coll = collect($validator->errors());
  10. $messages = $coll->flatten();
  11. foreach ($messages as $message) {
  12. echo $message . "\n";
  13. }
  14. }

该示例使用dateBefore规则验证两个日期。

  1. $validator = new Validator(['created_at' => '2019-03-01']);
  2. $validator->rule('dateBefore', 'created_at', '2018-10-13');

使用dateBefore规则,我们验证给定日期早于其他日期。

  1. $ php date_before.php
  2. Created At must be date before '2018-10-13'

This is the output.

验证 IP 地址

IP 地址使用ip规则进行验证。

ipaddress.php

  1. <?php
  2. require 'vendor/autoload.php';
  3. use Valitron\Validator;
  4. $vals = ['ip1' => '127.0.0.1', 'ip2' => 'FE80:0000:0000:0000:0202:B3FF:FE1E:8329',
  5. 'ip3' => 'FE80::0202:B3FF:FE1E:8329', 'ip4' => '0.0.1'];
  6. $coll = collect($vals);
  7. $coll->each(function ($value, $key) {
  8. $validator = new Validator([$key => $value]);
  9. $validator->rule('ip', $key);
  10. if ($validator->validate()) {
  11. echo "Validation passed for $key with $value" . "\n";
  12. } else {
  13. $errs = collect($validator->errors());
  14. $messages = $errs->flatten();
  15. foreach ($messages as $message) {
  16. echo $message . "\n";
  17. }
  18. }
  19. });

该示例验证 IP v4 IP v6 地址。

  1. $ php ipaddress.php
  2. Validation passed for ip1 with 127.0.0.1
  3. Validation passed for ip2 with FE80:0000:0000:0000:0202:B3FF:FE1E:8329
  4. Validation passed for ip3 with FE80::0202:B3FF:FE1E:8329
  5. Ip4 is not a valid IP address

This is the output.

自定义消息

我们可以提供自定义验证消息。 消息通过message()传递。

custom_message.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $validator = new Validator(['name' => '']);
  5. $validator->rule('required', 'name')->message('{field} is compulsory')->label("name");
  6. $validator->rule('lengthMin', 'name', 2)->message('{field} must have at least 2 characters')
  7. ->label("name");
  8. if($validator->validate()) {
  9. echo "Validation passed";
  10. } else {
  11. $coll = collect($validator->errors());
  12. $messages = $coll->flatten();
  13. foreach ($messages as $message) {
  14. echo $message . "\n";
  15. }
  16. }

该示例添加了自定义消息。

  1. $validator->rule('required', 'name')->message('{field} is compulsory')->label("name");

使用链接的方法调用,我们添加了自定义验证消息。

  1. $ php custom_message.php
  2. name is compulsory
  3. name must have at least 2 characters

This is the output.

值的验证子集

值的子集使用subset规则进行验证。

subsets.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $vals = ['colors' => ['green', 'blue', 'black']];
  5. $validator = new Validator($vals);
  6. $validator->rule('subset', 'colors', ['red', 'green', 'blue', 'orange', 'yellow']);
  7. if ($validator->validate()) {
  8. echo "Validation passed";
  9. } else {
  10. $coll = collect($validator->errors());
  11. $messages = $coll->flatten();
  12. foreach ($messages as $message) {
  13. echo $message . "\n";
  14. }
  15. }

该示例检查$vals变量是否包含来自定义的颜色值子集的颜色。

验证 GET 数据

在以下示例中,我们验证 GET 数据。

get_data.php

  1. <?php
  2. require('vendor/autoload.php');
  3. use Valitron\Validator;
  4. $validator = new Validator($_GET);
  5. $validator->rule('required', ['name', 'email']);
  6. $validator->rule('email', 'email');
  7. if ($validator->validate()) {
  8. echo "Validation passed";
  9. } else {
  10. $coll = collect($validator->errors());
  11. $messages = $coll->flatten();
  12. foreach ($messages as $message) {
  13. echo $message . "\n";
  14. }
  15. }

该示例验证来自 GET 请求的名称和电子邮件参数。

  1. $validator = new Validator($_GET);

全局$_GET变量传递给Validator

  1. $ php -S localhost:8000
  2. PHP 7.2.11 Development Server started at Sat Feb 23 17:24:05 2019
  3. Listening on http://localhost:8000
  4. Document root is C:\Users\Jano\Documents\php-progs\valitron
  5. Press Ctrl-C to quit.

我们启动内置的 Web 服务器。

  1. $ curl "localhost:8000/get_data.php?name=John%20Doe&email=john.doe#gmail.com"
  2. Email is not a valid email address

我们使用curl工具创建带有两个参数的 GET 请求。

您可能也对以下相关教程感兴趣: PHP Respect 验证教程PHP Rakit 验证教程PHP PDO 教程PHP 文件系统函数PHP 教程

在本教程中,我们使用了 Valitron 来验证 PHP 值。