仅在字段输入 Laravel 5.2 时验证

Validate only if the field is entered in Laravel 5.2

public function rules() {
        return [
            'num_of_devices' => 'integer'
        ];
}

当且仅当输入该字段时,我想验证一个整数字段。但是即使字段为空,上面的规则也会验证它是否为整数。我用了somtimes,但是没有结果。但是当我 var_dump($num_of_devices) 它是 string.I 正在使用 Laravel 5.2。我认为它在 5.1 中运行良好。

如果输入不为空,则向数组添加规则。您可以将所有验证规则收集到 $rules 数组,然后 return 数组。

if( !empty(Input::get('num_of_devices')) ){
  $rules['num_of_devices'] = 'integer';
}

您正在查找 sometimes 验证规则。来自文档:

…run validation checks against a field only if that field is present in the input array.

从版本 5.3 开始,您可以使用 nullable

public function rules() {
        return [
            'num_of_devices' => 'nullable | integer'
        ];
}