fuelphp/validation

此包已被弃用,不再维护。未建议替代包。

.

0.1.1 2016-11-25 16:35 UTC

This package is auto-updated.

Last update: 2023-01-30 20:27:50 UTC


README

Build Status Code Coverage Code Quality HHVM Status

一个灵活的库,用于验证不同类型的数据。

简单用法

<?php

use Fuel\Validation\Validator;

// Create a new validator instance to play with
$v = new Validator;

// Set up our required validation rules
$v->addField('name', 'User Name')
    ->required()
  ->addField('email', 'Email Address')
    ->required()
    ->email()
  ->addField('age', 'Current Age')
    ->number();

// Create some dummy data to validate
$data = array(
    'name' => 'John',
    'email' => 'john@doe.example',
    'age' => 32,
);

// Perform the validation
$result = $v->run($data);

var_dump($result->isValid()); // true
var_dump($result->getValidated()); // List of all the fields that passed validation

当前验证规则

所有核心规则类都可以在 Fuel\Validation\Rule 命名空间下找到。

  • email - 检查有效的电子邮件格式
  • ip - 检查有效的IP地址
  • matchField - 比较给定字段与另一个验证字段
  • minLength - 检查值是否大于等于给定值
  • maxLength - 检查值是否小于等于给定值
  • number - 检查值是否为数字
  • numericBetween - 检查数值是否在一个上下限范围内
  • numericMax - 检查值是否小于等于给定值
  • numericMin - 检查值是否大于等于给定值
  • regex - 检查值是否与给定的正则表达式匹配
  • required - 检查值是否存在于验证数据中
  • url - 检查给定的值是否是有效的URL
  • date - 检查给定的值是否与给定的日期格式匹配
  • type - 检查值是否是特定类型或参数的实例
  • enum - 检查值是否在允许的值列表中
  • enumMulti - 检查数组中的所有值是否在允许的值列表中
  • validator - 用于验证嵌套子模型

错误信息

在验证执行后,可以从结果对象中检索消息。

<?php

use Fuel\Validation\Validator;

// Create a new validator instance to play with
$v = new Validator;

// Set up our required validation rules
$v->addField('name', 'User Name')
    ->required()
  ->addField('email', 'Email Address')
    ->required()
    ->email()
  ->addField('age', 'Current Age')
    ->number();

// Create some dummy data to validate
$data = array(
    'email' => 'john',
    'age' => 'not a number',
);

// Perform the validation
$result = $v->run($data);

var_dump($result->isValid()); // false
var_dump($result->getValidated()); // array()

var_dump($result->getErrors()); // returns an array of all the error messages encountered
var_dump($result->getError('name')); // Returns the error message for the 'name' field

自定义消息

可以通过两种方式设置消息,直接在规则实例上或作为方法链的一部分。

use Fuel\Validation\Validator;

$v = new Validator;

$v->addField('name', 'User Name')
    ->required()
    ->setMessage('{label} is required, please enter a value');

现在当 required() 规则失败时,将使用自定义消息。

可以使用几个标记作为各种值的替代。例如,在示例中 {label} 将被替换为字段的标签,而 {name} 将被替换为字段的名称(如示例中所示)。规则还可以提供其他值,例如 NumericBetween 允许您使用 {upperBound}{lowerBound}。请参阅每个规则提供的自定义标记。

如果字符串中的标记未找到,则将简单地忽略它,而不会替换。

默认消息

可以通过在 Validator 对象上调用 setGlobalMessage() 来更改给定规则的默认消息。在此方法调用之后,通过 Validatator 通过魔法方法或 createRuleInstance() 创建的任何规则都将默认设置指定的消息。

use Fuel\Validation\Validator;

// Create a new validator instance to play with
$v = new Validator;

$v->setGlobalMessage('required', 'Sorry, my chum, but {label} is a required field and you did not enter anything');

手动添加规则和规则覆盖

除了使用默认的核心规则,还可以动态添加自己的规则或覆盖现有规则。

这可以通过在Validator对象上调用addCustomRule()函数来实现,例如:$v->addCustomRule('myCustomRule', 'My\App\Rules\CustomRule')。如果由于任何原因无法加载该类,当规则被使用时将抛出InvalidRuleException异常。

现在myCustomRule规则可用于与Validator实例一起使用,可以通过魔法方法语法或通过Validator中的createRuleInstance()函数来调用。

<?php

use Fuel\Validation\Validator;

// Create a new validator instance to play with
$v = new Validator;

$v->addCustomRule('myCustomRule', 'My\App\Rules\CustomRule');

// Example of adding the new rule via magic method syntax
$v->addField('foobar')
    ->myCustomRule();

$instance = $v->getRuleInstance('myCustomRule');
var_dump($instance); // instance of My\App\Rules\CustomRule

覆盖现有规则

可以通过像上一个例子中那样调用addCustomRule()并传递现有规则名称来简单地替换现有规则。

<?php

use Fuel\Validation\Validator;

// Create a new validator instance to play with
$v = new Validator;

$v->addCustomRule('required', 'My\App\Rules\CustomRule');

// Example of adding the new rule via magic method syntax
$v->addField('foobar')
    ->required();

$instance = $v->getRuleInstance('required');
var_dump($instance); // instance of My\App\Rules\CustomRule

嵌套验证器

可以使用验证器本身作为待验证数据条目的规则。这允许对父数据进行验证的同时也验证子模型。这可以通过使用Fuel\Validation\Rule\Validator规则来实现,并且可以嵌套到你想要的深度。

<?php

$childValidator = new Validator();
$childValidator
    ->addField('test')
    ->maxLength(5);

$parentValidator = new Validator();
$parentValidator
    ->addField('child')
    ->validator($childValidator);

$parentValidator
    ->addField('foobar')
    ->required();

$result = $parentValidator->run([
    'foobar' => 'test',
    // 'child' contains our child model data and is validted by $childValidator
    'child' => ['test' => '1234']
]);

自动Validator填充

通过使用RuleProvider类,可以自动为特定的Validator创建规则集,这可以用于自动创建任何类型对象的验证,从表单到ORM模型。目前只有一个提供者存在作为示例,它从配置数组中创建规则集。将来Fieldset和ORM将提供它们自己的提供者。

提供者是通过创建一个新的Validator,设置你的配置数组,然后填充Validator来使用的。

<?php

use Fuel\Validation\Validator;
use Fuel\Validation\RuleProvider\FromArray;

// The key is the name of the field that has a value of an array containing the rules
$config = array(
    'name' => array(
        'required', // Rules with no parameters can be specified like this
    ),
    'email' => array(
        'required',
        'email', // Make sure this is a valid email address
    ),
    'age' => array(
        'number',
        'numericMin' => 18, // Make sure the value is 18 or greater
    ),

    // The exact parameters for each rule are documented with the rule itself and can differ between rules.
);

$v = new Validator;

$generator = new FromArray;
$generator->setData($config)->populateValidator($v);

// $v is now populated with the fields and rules specified in the config array.

RuleProvider也会了解传递给它们的Validator中添加的自定义规则。

<?php

use Fuel\Validation\Validator;
use Fuel\Validation\RuleProvider\FromArray;

$config = array(
    'name' => array(
        'myCustomRule',
    ),
);

$v = new Validator;

$v->addRule('myCustomRule', 'My\App\Rules\CustomRule');

$generator = new FromArray;
$generator->setData($config)->populateValidator($v);

你还可以添加一个具有自定义结构的配置。

<?php

use Fuel\Validation\Validator;
use Fuel\Validation\RuleProvider\FromArray;

// The key is the name of the field that has a value of an array containing the rules
$config = array(
    'name' => array(
        'label' => 'Name'
        'validation' => array(
            'required',
        ),
    ),
    'email' => array(
        'label' => 'Email address',
        'validation' => array(
            'required',
            'email',
        ),
    ),
    'age' => array(
        'label' => 'Age',
        'validation' => array(
            'number',
            'numericMin' => 18,
        ),
    ),
);

$v = new Validator;

// First parameter: label key, default: disabled
// Second parameter: rules key, default: rules
$generator = new FromArray(true, 'validation'); // same as new FromArray('label', 'validation');
$generator->setData($config)->populateValidator($v);

// $v is now populated with the fields and rules specified in the config array.