本文介绍了如何在Laravel中验证整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组,例如 $ someVar = array(1,2,3,4,5).我需要验证 $ someVar 以确保每个元素都是数字.如何做到这一点?

I have an array of integer like this $someVar = array(1,2,3,4,5). I need to validate $someVar to make sure every element is numeric.How can I do that?

我知道,对于单值变量,验证规则将类似于以下 $ rules = array('someVar'=>'required | numeric').如何对数组 $ someVar 的每个元素应用相同的规则?

I know that for the case of a single valued variable, the validation rule would be something like this $rules = array('someVar'=>'required|numeric'). How can I apply the same rule to every element of the array $someVar?

非常感谢您的帮助.

推荐答案

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 方法.

Up to date version of this validation would not require the definition of numericarray method.

$rules = [
    'someVar'   => 'required|array',
    'someVar.*' => 'integer',
];

这篇关于如何在Laravel中验证整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 20:32