xentixar / validator
v1.0.0
2024-08-12 18:29 UTC
Requires
- php: ^8.0
README
Xentixar Validator是一个PHP验证库,它提供了一种基于各种规则的强大机制来验证数据。它包括一个用于发布配置文件的命令行工具和一个用于数据验证的Validator
类。
特性
- 支持使用如必填、电子邮件、最小值、最大值、唯一性等规则进行数据验证。
- 自定义错误消息。
- 与基于PDO的数据库集成,用于唯一性和存在性检查。
- 命令行工具用于管理配置文件。
安装
composer require xentixar/validator
配置
在使用验证器之前,您需要设置配置文件。
发布配置文件
运行以下命令将默认配置文件发布到您的项目中
cd vendor/xentixar/validator/bin
php xentixar publish:config
此命令将配置文件复制到config/vendor/validator
database.php
用于数据库连接设置。messages.php
用于自定义验证消息。
配置文件
config/vendor/validator/database.php
在此处提供您的数据库连接设置。示例
<?php return [ 'driver' => 'mysql', 'host' => '127.0.0.1', 'port' => '3306', 'database' => 'your_database', 'username' => 'your_username', 'password' => 'your_password', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', ];
config/vendor/validator/messages.php
为验证规则定义自定义错误消息。示例
<?php return [ 'required' => 'The :field field is required.', 'email' => 'The :field field must be a valid email address.', 'min' => 'The :field field must be at least :param characters.', 'max' => 'The :field field must not exceed :param characters.', 'between' => 'The :field field must be between :min and :max characters.', 'numeric' => 'The :field field must be a number.', 'integer' => 'The :field field must be an integer.', 'url' => 'The :field field must be a valid URL.', 'date' => 'The :field field must be a valid date (Y-m-d).', 'confirmed' => 'The :field confirmation does not match.', 'same' => 'The :field field must match the :param field.', 'unique' => 'The :field field must be unique.', 'exists' => 'The :field field does not exist.', 'in' => 'The :field field must be one of the following values: :values.', 'regex' => 'The :field field format is invalid.', 'size' => 'The :field field must be exactly :param characters.', 'date_format' => 'The :field field does not match the format :param.', 'file' => 'The :field field must be a valid uploaded file.', 'mimes' => 'The :field field must be a file of type: :types.', ];
用法
基本验证
以下是如何使用Validator
类的快速示例
use Xentixar\Validator\Validator; $validator = new Validator(); $data = [ 'email' => 'example@domain.com', 'password' => 'password123', ]; $rules = [ 'email' => 'required|email', 'password' => 'required|min:6', ]; if ($validator->validate($data, $rules)) { echo "Validation passed!"; } else { print_r($validator->errors()); }
错误消息
您可以在messages.php
配置文件中自定义错误消息。如果规则失败,验证器将使用这些消息。
命令行工具
可用命令
publish:config
:将默认配置文件复制到config/vendor/validator
目录。
运行命令
要运行命令,请使用
php xentixar [command]
例如
php xentixar publish:config
贡献
欢迎贡献!请遵循以下步骤
- 分支仓库。
- 创建一个功能分支(
git checkout -b feature/YourFeature
)。 - 提交您的更改(
git commit -am '添加新功能'
)。 - 推送到分支(
git push origin feature/YourFeature
)。 - 创建一个新的Pull Request。
许可证
此包采用MIT许可证。
联系
如有疑问或需要支持,请在GitHub上提交问题。