Laravel 8 JSON请求中is_active字段的严格整数验证问题
Laravel 8 严格校验JSON请求中的纯整数字段
Laravel 默认的 integer 验证规则会自动将字符串形式的数字(如 "1")转换为整数并通过校验,无法区分JSON中的字符串数字和纯整数。要实现仅接受不带引号的纯整数值(如 1/0),可以通过以下两种方式实现:
方法一:使用闭包验证规则
直接在验证逻辑中加入闭包,检查字段的原始类型是否为整数,同时验证值的范围:
use Illuminate\Http\Request; public function yourMethod(Request $request) { $validated = $request->validate([ 'is_active' => [ 'required', function ($attribute, $value, $fail) { // 严格校验类型为整数,且值为0或1 if (!is_int($value) || !in_array($value, [0, 1])) { $fail("The {$attribute} must be an integer (0 or 1) without quotes."); } }, ], ]); // 后续逻辑 }
方法二:自定义可复用的验证规则类
如果多个接口需要用到相同的严格整数校验,可以创建自定义规则类:
1. 生成规则类
执行Artisan命令创建规则文件:
php artisan make:rule StrictIntegerIn
2. 实现规则逻辑
修改生成的 app/Rules/StrictIntegerIn.php 文件:
namespace App\Rules; use Illuminate\Contracts\Validation\Rule; class StrictIntegerIn implements Rule { protected $allowedValues; // 初始化时传入允许的整数值数组 public function __construct(array $allowedValues) { $this->allowedValues = $allowedValues; } public function passes($attribute, $value) { // 校验值为整数类型,且在允许范围内 return is_int($value) && in_array($value, $this->allowedValues); } public function message() { return 'The :attribute must be a strict integer (without quotes) in the allowed values.'; } }
3. 使用自定义规则
在控制器中引用并使用该规则:
use Illuminate\Http\Request; use App\Rules\StrictIntegerIn; public function yourMethod(Request $request) { $validated = $request->validate([ 'is_active' => [ 'required', new StrictIntegerIn([0, 1]), ], ]); // 后续逻辑 }
说明:Laravel在解析JSON请求时会保留原始类型,因此JSON中的 "1" 会被解析为PHP字符串,1 会被解析为PHP整数,上述类型检查可以准确区分二者。
内容的提问来源于stack exchange,提问作者Arav
相关产品推荐
相关产品推荐

