PHP表单验证器是一个小巧的、无依赖的PHP代码库。

4.2.17 2024-08-22 05:31 UTC

README

Total Downloads Latest Stable Version License Code Coverage

文档

要求

  • >= php 8.0+

安装

在安装 validator 包 之前,请获取 PHP 依赖管理器 Composer,因为它将简化安装过程。

composer require tamedevelopers/validator

实例化 — 使用 实例化类

require_once __DIR__ . '/vendor/autoload.php';

use \Tamedevelopers\Validator\Validator;

$form = new Validator();
  • 或者 -- 辅助函数
$form = form();

Laravel 支持

  • 现在支持 Laravel,并且具有相同的函数性,没有区别
    • use Tamedevelopers\Validator\Validator;
public function save(Request $request){

    $form = new Validator();
    or
    $form = form();
}

应优先使用的方法

  • 所有这些方法都是可选的 方法
    • 这些方法仅在使用时是强制性的,并且应该始终在其他方法之前使用。
$form->post()->rules([
    // 
]);

全局配置

  • 可用的辅助工具可帮助轻松配置
    • config_form()
config_form(
    request       : 'POST',
    error_type    : true,
    csrf_token    : true,
    class         : [
        'error'     => 'alert alert-danger',
        'success'   => 'alert alert-success'
    ]
); 

CSRF

  • 实现 CSRF(跨站请求伪造)
    • 默认情况下,表单需要所有请求都附加一个令牌。
      • 您可以使用 config_form() 辅助工具禁用使用

CSRF 表单输入

  • 这将创建具有有效 csrf token 的 HTML 输入元素
    • 这是一个函数,您不需要 echo
      • 在您的 HTML 表单内部任何地方使用它
csrf();

Sample Csrf Form Input

CSRF 令牌

  • 这将返回 csrf token 字符串
csrf_token();

用法

  • 所有使用方法

错误类型

  • 接受一个 bool 类型的参数,默认为 false
    • 您可以选择单独调用,或者在调用其他任何方法之前调用,如果打算使用。
$form->errorType(false);

令牌

  • 接受一个 bool 类型的参数,默认为 false
    • 允许在每个表单请求上禁用 csrf_token
$form->token(false);

POST

  • 将表单请求设置为 POST
    • 这将始终覆盖 config_form() 设置
$form->post();

GET

  • 将表单请求设置为 GET
$form->get();

所有

  • 将自动检测请求类型是否为 GET\|POST 并获取其数据。
$form->all()->rules([
    // 
])

规则

  • 默认情况下,只需 数据类型[INPUT_NAME] 即可
    • 始终使用一个 '冒号' : 或 '竖线' | 将每个指示器分开
$form->rules([
    "string|country|==|0"   => 'Please Select a Country',
    "email:email"           => 'Please enter a valid email address',
])
  • HTML 表单结构
<form>
    <select name="country">
        <option value="0">Select Country</option>
        <option value="NGA">Nigeria</option>
        <option value="USA">United States of America</option>
    </select>

    <input type="hidden" name="_token" value="749c345a1d407f29e777349f5e46a8d6d2cd51454b6719228b5ee28f94c30432">
    <input type="email" name="email" placeholder="Email Address">
</form>

验证

  • 接受一个可选的 闭包 函数作为参数
$form->rules([
    "s:name" => 'Please enter a name',
])->validate(function($response){

    $response->param; //Collection of form data
    $response->getMessage(); //message property
});

保存

  • 期望一个 闭包 函数作为参数
    • 在成功时,消息属性将为空字符串 $response->message
$form->rules([
    "s:name" => 'Please enter a name',
])->save(function(){
    //on success
});

数据类型

  • 支持 9 种数据标志类型

运算符

  • 支持 10 种操作语句

noInterface

  • 期望一个 闭包 函数作为参数
    • 可以在不进行验证的情况下访问表单数据
$form->noInterface(function($response){

    if($response->has('amount')){
        // exec code
    }
});

之前

  • 期望一个 闭包 函数作为参数
    • 仅在请求类型为 [GET] 时执行代码
      • CSRF 令牌 不适用于此方法
$form->rules([
    "s:name" => 'Please enter a name',
])->before(function($response){

    // execute code
});

之后

  • 期望一个 闭包 函数作为参数
    • 无论请求方法类型如何,总会执行
      • CSRF 令牌 不适用于此方法
$form->after(function(){
    // execute code
});

有错误

  • 返回布尔值 true\|false
$form->hasError();

已验证

  • 返回布尔值 true\|false,当表单已验证时
$form->isValidated();

重置错误

  • 即使您在 success() 方法 内部
  • 使用此辅助工具,您可以将类重置为错误类
->save(function($response){

    $availableUserAmount = 900;

    <!-- Lets say for instance, users have wallet balance and the form request has no error -->
    <!-- But you need to perform another error validator before you allow request to pass through -->
    <!-- Don't forget the add the "return;" key to stop any other code from executing -->


    if($response->amount > $availableUserAmount){
        $response->reset();
        $response->message = "Your wallet balance is too low, Please recharge before you can Subscribe to Plan!";        
        return;
    }

    // perform other request before
});

  • 接受一个 数组 参数
    • 仅需要从 表单参数 中获取数据 keys
->save(function($response){
    //
    $data = $response->only(['password', 'username']);
});

除外

  • only() 方法的相反
->save(function($response){
    
    $data = $response->except(['_token']);
});

  • string 格式输入参数名
    • 返回布尔值 true|\false
->save(function($response){
    
    if($response->has('remeber_me')){
        // execute code
    }
});

  • string 格式输入参数,并返回旧插入的数据
    • 第二个参数是[可选的] mixed data
$form->rules([
    "s:password" => 'Please enter a name',
    "s:retype_pass:!==:{$form->old('password')}" => 'Password mismatch, Please enter same password',
]);
  • 或者 -- 辅助函数
<input type="email" name="email" value="<?= old('email', 'default_value')>">

Sample Session Schema

GetForm

  • array 形式返回所有提交的表单数据
->save(function($response){

    $data = $response->getForm();
});

合并

  • 与 PHP 函数 array_merge 相同
    • 将两个数组数据合并在一起
    • 第二个数据将始终替换第一个数组中匹配的键数据
->save(function($response){
    
    $data = [
        'name' => 'Lorem Name',
        'user_id' => rand(10000, 99999),
    ];

    $param = $response->merge($data, [
        'password' => md5($param['password'])
    ]);
});

只数据

  • 仅返回给定数组元素集合中通过的 data
->save(function($response){

    $data = $response->onlyData(['email', 'password'], [
        'email'     => 'mailer@mail.com', 
        '_token'    => md5('token'), 
        'age'       => 17,
        'password'  => 'test',
    ]);

    ---
    Only ['email', 'password'] will be returned.
});

除外数据

  • onlyData() 方法的相反
->save(function($response){
    
    $data = $response->exceptData(['_token'], [
        'email'     => 'mailer@mail.com', 
        '_token'    => md5('token'), 
        'password'  => 'test'
    ]);

    ---
    Return all array element, except ['_token']
});

获取信息和类

$form->getMessage();
$form->getClass();

Sample Session Schema

集合

  • 表单 param 返回一个 Collection 类
    • 这使我们能够将属性作为 objectarray index 访问
$form->rules([
    "string:country:==:0"   => 'Please Select a Country',
    "email:email"           => 'Please enter a valid email address',
])->save(function($response){

    $param = $response->param;


    $param->country;
    $param['country']

    ---
    As you can see, we're able to access data in both ways without errors
})

集合方法

toObject

  • mixed 格式输入参数
    • 转换为 Object 数据
$form->toObject([
    'food' => 'Basmati Rice'
]);

toArray

  • mixed 格式输入参数
    • 转换为 Array 数据
$form->toArray([
    'food' => 'Basmati Rice'
]);

toJson

  • mixed 格式输入参数
    • 转换为 Json 数据
$form->toJson([
    'food' => 'Basmati Rice'
]);

辅助工具

有用的链接