tagliatti/slim-validation

Slim PHP 微型框架的验证器

v4.0.0 2021-12-10 22:34 UTC

README

Build Status Latest Stable Version Total Downloads License

PHP 验证器,使用 Respect Validation v2.2 (需要 PHP 7+)

该项目最初是为与微型框架 "Slim" 一起使用而设计的,但现在可以与任何 psr/http-message 兼容的框架或任何其他 PHP 项目(如果不需要请求参数验证)一起使用。

安装

$ composer require Tagliatti/slim-validation

配置

要初始化验证器,创建一个新的 Tagliatti\SlimValidation\Validator 实例

Validator::__construct([ bool $showValidationRules = true [, array $defaultMessages = [] ]])
$showValidationRules
  • 如果设置为 true,错误将存储在一个关联数组中,验证规则名称作为键
$errors = [
    'username' => [
        'length' => 'The username must have a length between 8 and 16',
        'alnum' => 'The username must contain only letters (a-z) and digits (0-9)'
    ]
];
  • 如果设置为 false,错误将存储在一个字符串数组中
$errors = [
    'username' => [
        'The username must have a length between 8 and 16',
        'The username must contain only letters (a-z) and digits (0-9)'
    ]
];
$defaultMessages

要覆盖默认的 Respect Validation 消息的数组

$defaultMessages = [
    'length' => 'This field must have a length between {{minValue}} and {{maxValue}} characters',
    'notBlank' => 'This field is required'
];

添加验证器作为服务

您可以将验证器添加到应用容器中,以便通过您的应用程序轻松访问

$container['validator'] = function () {
    return new Tagliatti\SlimValidation\Validator();
};

用法

use Respect\Validation\Validator as V;

// The validate method returns the validator instance
$validator = $container->validator->validate($request, [
    'get_or_post_parameter_name' => V::length(6, 25)->alnum('_')->noWhitespace(),
    // ...
]);

if ($validator->isValid()) {
    // Do something...
} else {
    $errors = $validator->getErrors();
}

验证方法

请求参数验证

$_POST = [
    'username' => 'Tagliatti',
    'password' => 'my_password'
];
/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 */

$validator->request($request, [
    'username' => V::notBlank(),
    'password' => V::length(8)
]);

对象属性验证

class ObjectToValidate {
    private $privateProperty;
    protected $protectedProperty;
    public $pulicProperty;
    
    // ...
}
/**
 * @var object $object
 */

$validator->object($object, [
    'privateProperty' => V::notBlank(),
    'protectedProperty' => V::notBlank(),
    'publicProperty' => V::notBlank()
]);

如果属性不存在,测试的值将为 null

数组验证

$arrayToValidate = [
    'key_1' => 'value_1',
    'key_2' => 'value_2'
];
/**
 * @var array $arrayToValidate
 */

$validator->array($arrayToValidate, [
    'key_1' => V::notBlank(),
    'key_2' => V::notBlank()
]);

单个值验证

$validator->value('12345', V::numeric(), 'secret_code');

validate() 方法

/**
 * @var Psr\Http\Message\ServerRequestInterface $request
 */

$validator->validate($request, [
    'param' => V::notBlank()
]);

/**
 * @var object $object
 */

$validator->validate($object, [
    'property' => V::notBlank()
]);

/**
 * @var array $array
 */

$validator->array($array, [
    'key' => V::notBlank()
]);

$secretCode = '12345';
$validator->validate($secretCode, [
    'rules' => V::numeric(),
    'key' => 'secret_code'
]);

错误组

$user = [
    'username' => 'Tagliatti',
    'password' => 'my_password'
];

$address = [
    'street' => '...',
    'city' => '...',
    'country' => '...'
];

$validator->validate($user, [
    // ...
], 'user');

$validator->validate($address, [
    // ...
], 'address');
$validator->getErrors();

// Will return:
[
    'user' => [
        'username' => [
            // Errors...
        ]
    ],
    'address' => [
        'street' => [
            // Errors...
        ]
    ]
]

自定义消息

Slim Validation 允许您为验证错误设置自定义消息。有 4 种类型的自定义消息

默认规则消息

Validator 构造函数中定义的。

全局规则消息

在调用 validate 方法时,会覆盖 Respect Validation默认规则消息 的消息。

$container->validator->validate($request, [
    'get_or_post_parameter_name' => V::length(6, 25)->alnum('_')->noWhitespace(),
    // ...
], null, [
    'length' => 'Custom message',
    'alnum' => 'Custom message',
    // ...
]);

单个规则消息

单个请求参数的消息。覆盖所有上述消息。

$container->validator->validate($request, [
    'get_or_post_parameter_name' => [
        'rules' => V::length(6, 25)->alnum('_')->noWhitespace(),
        'messages' => [
            'length' => 'Custom message',
            'alnum' => 'Custom message',
            // ...
        ]
    ],
    // ...
]);

单个参数消息

为请求参数定义单个错误消息,忽略验证规则。覆盖所有消息。

$container->validator->validate($request, [
    'get_or_post_parameter_name' => [
        'rules' => V::length(6, 25)->alnum('_')->noWhitespace(),
        'message' => 'This field must have a length between 6 and 25 characters and contain only letters and digits'
    ],
    // ...
]);

Twig 扩展

此软件包包含一个 Twig 扩展,用于在您的 Twig 模板中显示错误消息和提交的值。如果您不想使用它,可以跳过此步骤。

要使用此扩展,您必须首先安装 twig

$ composer require slim/twig-view

配置

$container['view'] = function ($container) {
    // Twig configuration
    $view = new Slim\Views\Twig(...);
    // ...

    // Add the validator extension
    $view->addExtension(
        new Tagliatti\SlimValidation\ValidatorExtension($container['validator'])
    );

    return $view;
};

函数

{# Use has_errors() function to know if a form contains errors #}
{{ has_errors() }}

{# Use has_error() function to know if a request parameter is invalid #}
{{ has_error('param') }}

{# Use error() function to get the first error of a parameter #}
{{ error('param') }}

{# Use errors() function to get all errors #}
{{ errors() }}

{# Use errors() function with the name of a parameter to get all errors of a parameter #}
{{ errors('param') }}

{# Use val() function to get the value of a parameter #}
{{ val('param') }}

示例

AuthController.php
public function register(Request $request, Response $response)
{
    if ($request->isPost()) {
        $this->validator->validate($request, [
            'username' => V::length(6, 25)->alnum('_')->noWhitespace(),
            'email' => V::notBlank()->email(),
            'password' => [
                'rules' => v::length(6, 25),
                'messages' => [
                    'length' => 'This field must have a length between {{minValue}} and {{maxValue}} characters'
                ]
            ],
            'confirm_password' => [
                'rules' => v::equals($request->getParam('password')),
                'messages' => [
                    'equals' => 'The password confirmation must be equal to the password'
                ]
            ]
        ]);
        
        if ($this->validator->isValid()) {
            // Register user in database
            
            return $response->withRedirect('url');
        }
    }
    
    return $this->view->render($response, 'register.twig');
}
register.twig
<form action="url" method="POST">
    <input type="text" name="username" value="{{ val('username') }}">
    {% if has_error('username') %}<span>{{ error('username') }}</span>{% endif %}
    
    <input type="text" name="email" value="{{ val('email') }}">
    {% if has_error('email') %}<span>{{ error('email') }}</span>{% endif %}
    
    <input type="text" name="password">
    {% if has_error('password') %}<span>{{ error('password') }}</span>{% endif %}
    
    <input type="text" name="confirm_password">
    {% if has_error('confirm_password') %}<span>{{ error('confirm_password') }}</span>{% endif %}
</form>