验证Laravel 4错误中的数组表单字段 [英] Validation of array form fields in laravel 4 error
问题描述
我们如何验证数组的表单字段?看一下下面的代码
How can we validate form fields that are arrays? Take a look at the following code
UserPhone型号:
UserPhone Model:
public static $rules= array(
'phonenumber'=>'required|numeric',
'isPrimary'=>'in:0,1'
)
...........
UserController:
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);
}
}
$validation
来自扩展了Eloquent的BaseModel.
the $validation
comes from a BaseModel which extends Eloquent.
我认为:
<?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
一切正常,我可以在更新表格"中找到所有想要的电话号码,但是我无法更新模型,因为验证失败并显示消息电话号码必须是数字".
Everything is working fine and I get all the phone numbers I want in the Update Form, but I cannot update the model because the validation fails with the message "Phonenumber must be a number".
我知道没有简单的解决方案来验证数组表单字段,因此我尝试扩展Validator类,但没有成功.
I know that there is not a simple solution for validating array form fields and I tried to extend the validator class but with no success.
如何验证此类字段?
推荐答案
这是我使用的解决方案:
Here's the solution I use:
通过在前缀each
之前简单地变换您的常规规则.例如:
Simply transform your usual rules by prefixing each
. For example:
'names' => 'required|array|each:exists,users,name'
请注意,each
规则假定您的字段是一个数组,因此请不要忘记像之前显示的那样先使用array
规则.
Note that the each
rule assumes your field is an array, so don't forget to use the array
rule before as shown here.
错误消息将由您字段的单数形式(使用Laravel的str_singular()
帮助器)自动计算.在上一个示例中,属性为name
.
Error messages will be automatically calculated by the singular form (using Laravel's str_singular()
helper) of your field. In the previous example, the attribute is name
.
此方法对于点深度任意深度的嵌套数组都可以使用.例如,这有效:
This method works out of the box with nested arrays of any depth in dot notation. For example, this works:
'members.names' => 'required|array|each:exists,users,name'
同样,此处用于错误消息的属性将为name
.
Again, the attribute used for error messages here will be name
.
此方法开箱即用地支持您的任何自定义规则.
This method supports any of your custom rules out of the box.
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);
}
}
2.注册您的验证程序扩展名
在您通常的引导位置的任何地方,添加以下代码:
2. Register your validator extension
Anywhere in your usual bootstrap locations, add the following code:
Validator::resolver(function($translator, $data, $rules, $messages)
{
return new ExtendedValidator($translator, $data, $rules, $messages);
});
就是这样!享受吧!
正如评论所指出的那样,似乎没有简单的方法来验证数组大小.但是,Laravel文档缺少大小规则:没有提到它可以计算数组元素.这意味着您实际上被允许使用size
,min
,max
和between
规则对数组元素进行计数.
As a comment pointed out, there's seems to be no easy way to validate array sizes. However, the Laravel documentation is lacking for size rules: it doesn't mention that it can count array elements. This means you're actually allowed to use size
, min
, max
and between
rules to count array elements.
这篇关于验证Laravel 4错误中的数组表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!