跳转至

Valitron 教程

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

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

Valitron

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

安装

$ composer require vlucas/valitron
$ composer require tightenco/collect

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

简单的例子

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

simple.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

$validator = new Validator(['name' => 'John Doe']);
$validator->rule('required', 'name');

if($validator->validate()) {
    echo "Validation passed";
} else {

    $coll = collect($validator->errors());

    $messages = $coll->flatten();

    foreach ($messages as $message) {
        echo $message . "\n";
    }
}

该示例验证一个必需值。

use Valitron\Validator;

我们包括验证器。

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

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

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

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

if($validator->validate()) {

验证通过validate()执行。

$coll = collect($validator->errors());

$messages = $coll->flatten();

foreach ($messages as $message) {
    echo $message . "\n";
}

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

$ php simple.php
Validation passed

这是输出。

验证规则

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

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

multiple_rules.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

$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";
        }
    };
}

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

$rules = [
    'required' => ['name', 'email'],
    'alphaNum' => 'name',
    'integer' => 'age',
    'min' => [['age', 1]],
    'email' => 'email'
];

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

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

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

Valitron 链接规则

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

chaining.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

$validator = new Validator(['name' => 'John Doe', 'email' => 'johndoe#gmail.com']);
$validator->rule('required', 'name')->rule('email', 'email');

if($validator->validate()) {
    echo "Validation passed";
} else {

    $coll = collect($validator->errors());

    $messages = $coll->flatten();

    foreach ($messages as $message) {
        echo $message . "\n";
    }
}

该示例链接了两个规则。

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

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

验证日期

日期有四个验证规则:datedateFormatdateBeforedateAfter

date_before.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

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

if ($validator->validate()) {
    echo "Validation passed";
} else {

    $coll = collect($validator->errors());

    $messages = $coll->flatten();

    foreach ($messages as $message) {
        echo $message . "\n";
    }
}

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

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

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

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

This is the output.

验证 IP 地址

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

ipaddress.php

<?php

require 'vendor/autoload.php';

use Valitron\Validator;

$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'];

$coll = collect($vals);
$coll->each(function ($value, $key) {

    $validator = new Validator([$key => $value]);
    $validator->rule('ip', $key);

    if ($validator->validate()) {
        echo "Validation passed for $key with $value" . "\n";
    } else {
        $errs = collect($validator->errors());

        $messages = $errs->flatten();

        foreach ($messages as $message) {
            echo $message . "\n";
        }
    }
});

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

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

This is the output.

自定义消息

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

custom_message.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

$validator = new Validator(['name' => '']);
$validator->rule('required', 'name')->message('{field} is compulsory')->label("name");
$validator->rule('lengthMin', 'name', 2)->message('{field} must have at least 2 characters')
        ->label("name");

if($validator->validate()) {
    echo "Validation passed";
} else {

    $coll = collect($validator->errors());

    $messages = $coll->flatten();

    foreach ($messages as $message) {
        echo $message . "\n";
    }
}

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

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

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

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

This is the output.

值的验证子集

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

subsets.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

$vals = ['colors' => ['green', 'blue', 'black']];

$validator = new Validator($vals);

$validator->rule('subset', 'colors', ['red', 'green', 'blue', 'orange', 'yellow']);

if ($validator->validate()) {
    echo "Validation passed";
} else {

    $coll = collect($validator->errors());

    $messages = $coll->flatten();

    foreach ($messages as $message) {
        echo $message . "\n";
    }
}

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

验证 GET 数据

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

get_data.php

<?php

require('vendor/autoload.php');

use Valitron\Validator;

$validator = new Validator($_GET);
$validator->rule('required', ['name', 'email']);
$validator->rule('email', 'email');

if ($validator->validate()) {
    echo "Validation passed";
} else {

    $coll = collect($validator->errors());

    $messages = $coll->flatten();

    foreach ($messages as $message) {
        echo $message . "\n";
    }
}

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

$validator = new Validator($_GET);

全局$_GET变量传递给Validator

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

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

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

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

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

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


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组