Laravel 验证:仅当存在另一个字段时才验证字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33106512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:29:55  来源:igfitidea点击:

Laravel validation: validate field only if another is present

phpvalidationlaravel

提问by dani24

I wanted to validate an 'account_id' only if 'needs_login' is present. I did this:

我想仅在存在“needs_login”时验证“account_id”。我这样做了:

$rules = [
    'account_id' => ['required_with:needs_login','custom_validation']
];

But it doesn't work, because if needs_login field is not present but account_id has some value, then it tries to do the 'custom_validation'. I also tried to put the 'sometimes' parameter

但它不起作用,因为如果 Needs_login 字段不存在但 account_id 有一些值,那么它会尝试执行“custom_validation”。我也试图把“有时”参数

$rules = [
    'account_id' => ['required_with:needs_login', 'sometimes', 'custom_validation']
];

but it didn't work.

但它没有用。

Any ideas?

有任何想法吗?

P.S.:Remember that I wanted to validate the account_id only if needs_login is present, not to check if account_id is present if needs_login does.

PS:请记住,我只想在需要登录时验证 account_id,而不是在需要登录时检查 account_id 是否存在。

采纳答案by DonnaJo

Something like this works for Laravel 5 if you are going the 'sometimes' route. Perhaps you can adapt for L4? Looks like it's the same in the Docs.

如果您要走“有时”路线,这样的事情适用于 Laravel 5。也许你可以适应L4?看起来它在 Docs 中是一样

$validation = Validator::make($formData, [
    'some_form_item' => 'rule_1|rule_2'
]
$validation->sometimes('account_id', 'required', function($input){
    return $input->needs_login == true;
});

回答by IllegalPigeon

Have you tried required_if?

你试过required_if吗?

$rules = [
    'account_id' => ['required_if:needs_login,1']
];