Laravel中如何设置type_id为0-4整数的验证规则?
Laravel表单验证:限制type_id为0-4的整数
问题描述
我在Blade模板的表单里有个type_id字段,要求它的值必须是0到4之间的整数,只有符合要求才存储数据。想咨询能不能设置多值的size验证规则,比如写成'size:0 || size:1 || size:2 || size:3 || size:4'?以下是我的store方法代码:
public function store(Request $request) { $toCreate = $request->validate([ 'type_id' => ['required','integer','size:4'], 'name' => ['required', 'string', 'max:255'], 'partitaIva' => ['max:255'], 'codiceFiscale' => ['max:255'], 'sedeAmministrativa' => ['max:255'], 'indirizzoNotifica' => ['max:255'], 'referente' => ['max:255'], 'responsabile' => ['max:255'], 'telefono' => ['max:255'], 'fax' => ['max:255'], 'email' => ['max:255'], 'pec' => ['max:255'], 'capitale' => ['max:255'], 'nDipendenti' => ['max:255'], 'convenzioniDeleghe' => [], 'note' => [] ]); Administration::create($toCreate); return redirect()->route('administrations.index')->with('success','Amministratore aggiunto con successo.'); }
解决方案
你不能用size:0 || size:1这种写法,Laravel的验证规则不支持这种语法。针对你的需求,有两种更合适的方案:
方案一:用in规则指定允许的离散值
in规则可以直接限定字段值必须是给定列表中的某一个,完全匹配你的需求:
'type_id' => ['required', 'integer', 'in:0,1,2,3,4'],
方案二:用min+max规则限定数值范围
如果你的需求是0到4之间的所有整数(包含边界),也可以用范围规则组合:
'type_id' => ['required', 'integer', 'min:0', 'max:4'],
修改后的完整store方法
public function store(Request $request) { $toCreate = $request->validate([ 'type_id' => ['required','integer','in:0,1,2,3,4'], // 替换为上述任意一种规则即可 'name' => ['required', 'string', 'max:255'], 'partitaIva' => ['max:255'], 'codiceFiscale' => ['max:255'], 'sedeAmministrativa' => ['max:255'], 'indirizzoNotifica' => ['max:255'], 'referente' => ['max:255'], 'responsabile' => ['max:255'], 'telefono' => ['max:255'], 'fax' => ['max:255'], 'email' => ['max:255'], 'pec' => ['max:255'], 'capitale' => ['max:255'], 'nDipendenti' => ['max:255'], 'convenzioniDeleghe' => [], 'note' => [] ]); Administration::create($toCreate); return redirect()->route('administrations.index')->with('success','Amministratore aggiunto con successo.'); }
补充说明
size规则验证整数时,仅要求字段值严格等于指定数值,不支持多值或逻辑或的写法;- 两种方案的选择:明确知道允许的离散值用
in,连续数值范围用min/max,根据实际场景选即可。
内容的提问来源于stack exchange,提问作者Matteo Cossu
相关产品推荐
相关产品推荐

