在laravel 4错误中验证数组表单字段

Arc*_*s M 14 laravel laravel-4

我们如何验证作为数组的表单字段?看看下面的代码

UserPhone型号:

 public static $rules= array(
    'phonenumber'=>'required|numeric',
    'isPrimary'=>'in:0,1'
)
...........
Run Code Online (Sandbox Code Playgroud)

UserController的:

$validation = UserPhone::validate(Input::only('phonenumber')));


    if($validation->passes())
      {
         $allInputs = Input::only('phonenumber','tid');
         $loopSize = sizeOf($allInputs);

         for($i=0;$i<$loopSize;$i++)
         {

         $phone = UserPhone::find($allInputs['tid'][$i]);
         $phone->phonenumber = $allInputs['phonenumber'][$i];
         $phone->save();

        }

     return Redirect::to('myprofile')->with('message','Update OK');

  }
  else
  {
     return Redirect::to('editPhone')->withErrors($validation);

  } 

}
Run Code Online (Sandbox Code Playgroud)

对$validation来自延伸洋洋洒洒一BaseModel.

在我看来:

 <?php $counter=1; ?>
          @foreach($phones as $thephone)

           <section class="col col-12">
              <label class="label">Phone Number {{$counter++}}</label>
              <label class="input">
              <i class="icon-append icon-phone"></i>
                 {{Form::text('phonenumber[]',$thephone->phonenumber)}}
                 {{Form::hidden('tid[]',$thephone->id)}}
              </label>
            </section>
          @endforeach
Run Code Online (Sandbox Code Playgroud)

一切正常,我在更新表单中获得了我想要的所有电话号码,但我无法更新模型,因为验证失败并显示消息"Phonenumber必须是一个数字".

我知道没有一个简单的解决方案来验证数组表单字段,我试图扩展验证器类但没有成功.

我该如何验证这种字段?

Laz*_*zlo 25

这是我使用的解决方案:

用法

只需通过前缀改变您的常规规则each.例如:

'names' => 'required|array|each:exists,users,name'
Run Code Online (Sandbox Code Playgroud)

请注意,该each规则假定您的字段是一个数组,因此请不要忘记使用array之前的规则,如此处所示.

错误消息

错误消息将通过str_singular()您的字段的单数形式(使用Laravel的帮助程序)自动计算.在前面的示例中,属性是name.

嵌套数组

此方法开箱即用,带有点符号的任何深度的嵌套数组.例如,这有效:

'members.names' => 'required|array|each:exists,users,name'
Run Code Online (Sandbox Code Playgroud)

同样,这里用于错误消息的属性将是name.

自定义规则

此方法支持开箱即用的任何自定义规则.

履行

1.扩展验证器类

class ExtendedValidator extends Illuminate\Validation\Validator {

    public function validateEach($attribute, $value, $parameters)
    {
        // Transform the each rule
        // For example, `each:exists,users,name` becomes `exists:users,name`
        $ruleName = array_shift($parameters);
        $rule = $ruleName.(count($parameters) > 0 ? ':'.implode(',', $parameters) : '');

        foreach ($value as $arrayKey => $arrayValue)
        {
            $this->validate($attribute.'.'.$arrayKey, $rule);
        }

        // Always return true, since the errors occur for individual elements.
        return true;
    }

    protected function getAttribute($attribute)
    {
        // Get the second to last segment in singular form for arrays.
        // For example, `group.names.0` becomes `name`.
        if (str_contains($attribute, '.'))
        {
            $segments = explode('.', $attribute);

            $attribute = str_singular($segments[count($segments) - 2]);
        }

        return parent::getAttribute($attribute);
    }
}
Run Code Online (Sandbox Code Playgroud)

2.注册您的验证器扩展

在通常的引导位置中的任何位置,添加以下代码:

Validator::resolver(function($translator, $data, $rules, $messages)
{
    return new ExtendedValidator($translator, $data, $rules, $messages);
});
Run Code Online (Sandbox Code Playgroud)

就是这样!请享用!

额外:使用数组的大小规则

正如评论指出的那样,似乎没有简单的方法来验证数组大小.但是,Laravel文档缺少大小规则:它没有提到它可以计算数组元素.这意味着你实际上允许使用size,min,max和between规则来计算数组元素.


Ron*_*hof 9

最好扩展Validator类并重用现有的Validator函数:

Validator::resolver(function($translator, $data, $rules, $messages)
{

    return new Validation($translator, $data, $rules, $messages);

});

class Validation extends Illuminate\Validation\Validator {

    /**
     * Magically adds validation methods. Normally the Laravel Validation methods
     * only support single values to be validated like 'numeric', 'alpha', etc.
     * Here we copy those methods to work also for arrays, so we can validate
     * if a value is OR an array contains only 'numeric', 'alpha', etc. values.
     *
     * $rules = array(
     *     'row_id' => 'required|integerOrArray', // "row_id" must be an integer OR an array containing only integer values
     *     'type'   => 'inOrArray:foo,bar' // "type" must be 'foo' or 'bar' OR an array containing nothing but those values
     * );
     *
     * @param string $method Name of the validation to perform e.g. 'numeric', 'alpha', etc.
     * @param array $parameters Contains the value to be validated, as well as additional validation information e.g. min:?, max:?, etc.
     */
    public function __call($method, $parameters)
    {

        // Convert method name to its non-array counterpart (e.g. validateNumericArray converts to validateNumeric)
        if (substr($method, -7) === 'OrArray')
            $method = substr($method, 0, -7);

        // Call original method when we are dealing with a single value only, instead of an array
        if (! is_array($parameters[1]))
            return call_user_func_array(array($this, $method), $parameters);

        $success = true;
        foreach ($parameters[1] as $value) {
            $parameters[1] = $value;
            $success &= call_user_func_array(array($this, $method), $parameters);
        }

        return $success;

    }

    /**
     * All ...OrArray validation functions can use their non-array error message counterparts
     *
     * @param mixed $attribute The value under validation
     * @param string $rule Validation rule
     */
    protected function getMessage($attribute, $rule)
    {

        if (substr($rule, -7) === 'OrArray')
            $rule = substr($rule, 0, -7);

        return parent::getMessage($attribute, $rule);

    }
}
Run Code Online (Sandbox Code Playgroud)


sko*_*cs1 6

每()

它不在文档中,但4.2分支可能在第220行附近有一个简单的解决方案.

就像这个sometimes($attribute, $rules, callable $callback)功能一样,现在有一个each($attribute, $rules)功能.

要使用它,代码将比sometimes()调用更简单:

$v->each('array_attribute',array('rule','anotherRule')); //$v is your validator
Run Code Online (Sandbox Code Playgroud)

注意事项

  • sometimes()并且each()似乎不容易相互链接,所以如果你想对数组值做专门的条件规则,你现在最好用其他答案中的魔术解决方案.
  • each()只有一个深度,与其他解决方案没有什么不同.关于神奇解决方案的好处在于它们会根据需要通过调用基本规则来达到0或1级深度,所以我想如果你想要深入1到2级,你可以简单地通过调用each()和合并这两种方法.从其他答案传递一个魔法规则.
  • each()只需要一个属性,而不是一个属性的阵列sometimes()做,但添加此功能each()不会到一个巨大的变化each()的功能-只要通过循环$attribute与array_merge() $data和array_get()结果.有人可以将它作为主要的拉取请求,如果他们认为它是可取的并且尚未完成,我们可以看到它是否成为未来的构建.