yuri-oliveira / validate
用于执行验证的包
v1.0.8
2023-04-13 00:47 UTC
Requires
- php: >=7.4
README
该项目是一个PHP组件,用于执行验证。
安装
composer require yuri-oliveira/validate
如何使用
验证
<?php use YuriOliveira\Validate\Validate; require_once(__DIR__ . '/vendor/autoload.php'); $data = [ 'name' => 'Anthony Edward Stark Jr', 'email' => 'TonyEsterco@hotmail.com', 'password' => '', ]; $validate = Validate::create($data); $validate->validate([ 'name' => ['max:250', 'required'], 'email' => ['email', 'required'], 'password' => ['min:8', 'max:100', 'required'] ]); print_r($validate->errors()); // Retorno de erros // [ // 'password' => 'O campo password deve conter no mínimo 8 caracteres.' // ];
验证条件
条件之后的所有内容只有在条件满足时才会被验证。
$validate->validate([ 'email' => ['condition:filled', 'email'] 'password' => ['condition:empty', 'required'] ]);
创建自定义条件。
注意:条件必须始终返回一个布尔值。如果返回 true,则表示验证应该继续,如果返回 false,则验证将被中断。
<?php use YuriOliveira\Validate\Condition; require_once(__DIR__ . '/vendor/autoload.php'); Condition::extend('custom', function($value, $key) { return is_string($value) ? true : false; });
错误信息
包含错误信息的文件是一个关联数组,其中键是错误,值是消息。某些错误可能需要数据类型(字符串、数字、文件和数组)的过滤器。以下是一个错误信息文件的示例。
return [ 'required' => 'O campo :attribute é obrigatório.', 'email' => 'O campo :attribute deve conter um email válido.', 'max' => [ 'string' => 'O campo :attribute deve conter no máximo :max caracteres.', 'file' => 'O arquivo :attribute deve ter o tamanho máximo de :max.' ] ];
我们还可以使用 "Message" 类的 "extend" 方法插入更多自定义错误信息。
<?php use YuriOliveira\Validate\Message\Message; require_once(__DIR__ . '/vendor/autoload.php'); $customMessages = [ 'custom' => 'O campo :attribute é customizado' ]; Message::extend($customMessages);
要获取消息,我们使用 "get" 方法。
简单消息
Message::get('required', 'email'); // resultado: O campo email é obrigatório.
具有类型和参数的消息
Message::get('max.string', 'password', 25); // resultado: O campo password deve conter no máximo 25 caracteres.
自定义验证
如果发生错误,验证应该返回一个消息(我们可以通过 Message 类获取,并使用前面示例中创建的消息)如果通过,则返回 "true"。
Validate::extend('custom', function($key, $value) { if (!is_string($value)) { return Message::get('custom', $key); } return true; });
要求
- PHP 7.4 或更高版本