doujiang1001 2013-05-29 16:59
浏览 14

使用L4验证器的嵌套输入

Does anyone know how to validate nested input sets using the Laravel 4 validator?

I have a table with a set of line items, and each quantity field has the unique package id in square brackets in the name:

<input type="text" name="quantity[package_one]" />
<input type="text" name="quantity[package_two]" />

This results in a nested input array:

<?php

array(
  'quantity' => array(
    'package_one' => 3,
    'package_two' => 12
  )
);

Which is exactly what i want, but i'm unsure how to specify rules for these items using the validator class:

// Does not work :-(
Validator::make(Input::all(), array(
    'quantity[package_one]' => 'numeric|required|min:1',
    'quantity[package_two]' => 'numeric|required|min:1'
));

This does not seem to work, neither does nesting the rules under quantity. Obviously there are workarounds to this like building a custom array of input yourself before passing it to the validator etc, but what i'd like to know is:

is there a native, "Laravel" way of handling nested input like this?

Thanks in advance, Dan.

  • 写回答

2条回答 默认 最新

  • donglue1886 2013-05-29 17:40
    关注

    The dirty way....

    Controller

    $input = Input::all();
    $input = array_merge($input, $input['quantity']);
    Validator::make(Input::all(), array(
    'package_one' => 'numeric|required|min:1',
    'package_two' => 'numeric|required|min:1'
     ));
    

    Validator does not look into nested arrays. just bring that array to the outer one and you are done. (you can unset $input['quntity'] if you want after that)

    loophole here is, it assumes that $input['quantity'] is present in the array. You need to validate this before putting into validation.

    Works but not efficient.

    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入