我有一个像这样的整数数组$someVar = array(1,2,3,4,5)
。我需要验证$someVar
以确保每个元素都是数字。我该怎么做呢?
我知道对于单值变量的情况,验证规则将类似于$rules = array('someVar'=>'required|numeric')
。我如何将相同的规则应用于数组$someVar
的每个元素?
谢谢你的帮助。
现在laravel有选项来设置数组元素的条件。不需要为像验证int数组这样简单的事情编写自己的验证器。使用这个(如果在控制器中使用)-
$validator = 'Validator::make(compact('someVar'), [
'someVar' => 'required|array',
'someVar.*' => 'integer'
]);
$this->validateWith($validator);
或
$this->validate($request, [
'someVar' => 'array',
'someVar.*' => 'int'
]);
Validator::extend('numericarray', function($attribute, $value, $parameters)
{
foreach($value as $v) {
if(!is_int($v)) return false;
}
return true;
});
使用它$rules = array('someVar'=>'required|array|numericarray')
编辑:此验证的最新版本不需要定义numericarray
方法。
$rules = [
'someVar' => 'required|array',
'someVar.*' => 'integer',
];
在Laravel 5中,你可以使用.*
来检查数组中的元素。对你来说,这意味着:
$rules = array('someVar' => 'required|array',
'someVar.*' => 'integer')
首先添加一个新的验证属性
Validator::extend('numeric_array', function($attribute, $values, $parameters)
{
if(! is_array($values)) {
return false;
}
foreach($values as $v) {
if(! is_numeric($v)) {
return false;
}
}
return true;
});
如果attribute不是数组或者其中一个值不是数值,函数将返回false。然后添加消息到' app/lang/en/validation.php'
"numeric_array" => "The :attribute field should be an array of numeric values",
您可以为数组
添加整数类型值检查的自定义规则打开文件
/resources/lang/en/validation.php
在文件中"已接受"消息之前添加自定义消息。
'numericarray' => 'The :attribute must be numeric array value.',
"accepted" => "The :attribute must be accepted.",
打开文件
/app/Providers/AppServiceProvider.php
,然后在启动函数中添加自定义验证。
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
}
现在可以使用numericarray对数组
进行整型值检查$this->validate($request, [
'field_name1' => 'required',
'field_name2' => 'numericarray'
]);
只有'array'验证确保值是一个数组,但对于您的特定情况,您将不得不创建一个自定义过滤器:
Laravel 3: http://three.laravel.com/docs/validation#custom-validation-rules
Laravel 4: http://laravel.com/docs/validation#custom-validation-rules
AppServiceProvider.php
Validator::extend('integer_array', function($attribute, $value, $parameters)
{
return Assert::isIntegerArray($value);
});
Assert.php
/**
* Checks wheter value is integer array or not
* @param $value
* @return bool
*/
public static function isIntegerArray($value){
if(!is_array($value)){
return false;
}
foreach($value as $element){
if(!is_int($element)){
return false;
}
}
return true;
}