danielz/shape-validator-php

简单的(数组)形状验证器。

v1.0.0 2022-01-28 12:20 UTC

This package is auto-updated.

Last update: 2024-08-28 17:27:05 UTC


README

为形状定义所有可能的字段并设置其规则。任何不在定义集中的字段都会触发错误。

用法

try {
    $shape = [
        'name' => 'required|string',
        'phone' => 'required|numeric',
        'notes' => 'string',
        'data' => 'any',
    ];
    $shape_validator = new ShapeValidator($shape);
    $shape_validator->validate([
        'name' => 'Hello, world!', // valid
        'extra' => null, // this will trigger an error    
    ]);
} catch(ShapeException $exception) {
    // getValidationErrors() returns an array like ['field name' => 'error message']
    log($exception->getValidationErrors());
}

可用规则

  • required - 字段必须存在
  • nullable - 字段可以接受null值
  • string - 如果字段值已设置,它必须是一个有效的字符串
  • numeric- 如果字段值已设置,它必须具有有效的数值
  • bool / boolean - 如果字段值已设置,它必须是一个有效的布尔值(验证使用类型比较 ===
  • any - 允许任何值