安装 github.com/square/laravel-hyrule
composer require square/laravel-hyrule
是一个面向对象的、可组合的、流畅的 API,用于在 Laravel 中编写验证
Hyrule 通过提供一个构建器对象来工作,该对象允许您围绕预期的表单字段构建规则。这些字段可以是简单的标量数据类型和复杂的数组和对象。例如,这是一个基本规则,验证名字是最大长度为 255 个字符的必需字符串:
// Initialize a new builder | |
$builder = Hyrule::create(); | |
// Describe your expected input: | |
$builder->string('first_name') | |
->required() | |
->max(255); | |
$rules = $builder->build(); | |
$validator = Validator::make($data, $rules); |
大多数表单提交多个字段,为了遍历多个字段,您可以使用以下end()方法将它们链接在一起:
$builder | |
->string('first_name') | |
->required() | |
->max(255) | |
->end() | |
->string('last_name') | |
->required() | |
->max(255) | |
->end() | |
->integer('age') | |
->required() | |
->min(21) | |
->max(60) | |
->end(); |
您不仅可以为标量字段定义验证,此包还允许您验证对象、标量字段数组和对象数组:
$builder | |
->object('nutritional_facts') | |
->required() | |
->integer('servings_per_container') | |
->required() | |
->min(1) | |
->end() | |
->string('serving_size') | |
->required() | |
->min(1) | |
->max(30) | |
->end() | |
->object('fat') | |
->integer('saturated_fat_grams')->end() | |
->integer('saturated_fat_percent') | |
->max(100) | |
->end(); | |
->end(); |