申请“存在";验证Laravel中的可选字段 [英] Apply "exists" validation for optional field in Laravel

查看:61
本文介绍了申请“存在";验证Laravel中的可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Laravel 5.4中开发一个项目,我想对两个可选字段(仅当提供值时)进行存在"验证规则.

I am working on a project in Laravel 5.4 and i want to do a "exists" validation rule on two optional fields (only when a value is supplied).

我尝试了以下操作:

// Define validation rules
$validator = Validator::make($request->all(), [
    'user_group_id' => 'sometimes|exists:groups,id',
    'user_organisation_id' => 'sometimes|exists:organisations,id',
    // my other required fields here...
]);

// Validate store request
if ($validator->fails())
    return redirect()
        ->back()
        ->withErrors($validator)
        ->withInput();

在我的应用程序中,用户并不总是属于一个团体或组织.因此,当我提交表单而不选择组/组织时,我希望验证不会执行,但是它是-我遇到以下错误:

In my application, user's will not always belong to an group or an organisation. So, when I submit my form without selecting a group/organisation, I expected the validation to not execute, however it is - I am getting the following errors:

The selected user group id is invalid.
The selected user organisation id is invalid.

仅在提供值时,如何使存在"验证规则适用?使用有时"标志似乎无效.

How do you make the "exists" validation rule to apply, only when a value is supplied? using the "sometimes" flag doesn't seem to be working.

我尝试了类似的方法,但它似乎正在起作用:

I tried something like this and it appears to be working:

// Define validation rules
if (!empty($request->user_group)) $rules['user_group'] = 'exists:groups,id';
if (!empty($request->user_organisation)) $rules['user_organisation'] = 'exists:organisations,id';
$rules = [
    // normal required field validations here
];
$validator = Validator::make($request->all(), $rules);

这是获得条件验证的唯一方法吗?

Is this the only way to achieve my conditional validation?

推荐答案

我通常将有时 required 一起使用我尚未确认/证明为什么我需要使用它但是,我最终得到这样的东西:

I normally use sometimes with required I have not affirmed/proven why I need the required with it though, so I end up with something like this:

'user_group_id' => 'sometimes|required|exists:groups,id',

PS:根据我对Laravel的少量经验,我也遇到了类似的情况.从 https://laravel.com/docs/5.2/validation#conditionally-添加规则

这篇关于申请“存在";验证Laravel中的可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆