open-core/validator

基于属性和内部 DSL 的简单、快速且轻量级验证器

dev-main 2024-04-18 12:59 UTC

This package is auto-updated.

Last update: 2024-09-18 13:50:21 UTC


README

基于属性和内部 DSL 的简单、快速且轻量级验证器

主要功能

  • 使用 PHP 属性的 API 高级使用和内部 DSL 的 API 低级使用
  • 支持嵌套类型化结构
  • 支持嵌套和类型化数组
  • 反序列化

示例

拥有一些复杂的模型

class LoginApplicationForm {

  #[LenBetween(3, 16)]
  public string $login;

  #[LenBetween(8, 16)]
  public string $password;
}

class GuestApplicationForm {

  public LoginApplicationForm $userLogin;

  public bool $acceptTerms = false;

  #[Email]
  #[LenBetween(5, 24)]
  public ?string $email;

  #[CountBetween(1, 5)]
  #[Each([new LenBetween(3, 16)])]
  #[Arr(Type::STRING)]
  public array $interests = [];

  #[Key('q1', [new Optional([new LenBetween(0, 16)])])]
  #[Key('q2', [new LenBetween(1, 32)])]
  #[Key('q3', [new Between(0, 100)])]
  #[Arr(Type::MIXED)]
  public array $survey;
}

以及用户输入

$userInput=[
  'userLogin' => [
    'login' => 'mylogin',
    'password' => '$mypass657$',
  ],
  'acceptTerms' => true,
  'email' => 'user@example.com',
  'phone' => '+000 000-000-000',
  'interests' => ['music', 'movie'],
  'survey' => ['q1' => 'yes', 'q2' => 'I dont know', 'q3' => 42],
];

根据模型验证数据

try{
  Validator::validateByModel(GuestApplicationForm::class, $userInput);
}catch(ValidationException $ex){
  print_r($ex->result->inspect());
}

甚至在验证后反序列化为对象

try{
  $form = Validator::deserialize(GuestApplicationForm::class, $userInput);
}catch(ValidationException $ex){
  print_r($ex->result->inspect());
}