简体   繁体   English

Laravel 验证:仅需要且只有一个字段

[英]Laravel validation: Required only and only one field

I have got two fields namely number and percentage.我有两个字段,即数字和百分比。 I want a user to input value in only one input field.我希望用户只在一个输入字段中输入值。 If a user inputs values in both number and percentage field, the system should throw validation error.如果用户在数字和百分比字段中输入值,系统应该抛出验证错误。 Is there anything we can do with laravel validation to achieve this?我们可以用 laravel 验证做些什么来实现这一点吗?

Thanks.谢谢。

You can write a custom validator for that: http://laravel.com/docs/5.0/validation#custom-validation-rules 您可以为此编写自定义验证器: http//laravel.com/docs/5.0/validation#custom-validation-rules

It may looks somthing like this: 它可能看起来像这样:

class CustomValidator extends Illuminate\Validation\Validator {

    public function validateEmpty($attribute, $value)
    {
        return ! $this->validateRequired($attribute, $value);
    }

    public function validateEmptyIf($attribute, $value, $parameters)
    {
        $key = $parameters[0];

        if ($this->validateRequired($key, $this->getValue($key))) {
            return $this->validateEmpty($attribute, $value);
        }

        return true;
    }
}

Register it in a service provider: 在服务提供商中注册:

Validator::resolver(function($translator, $data, $rules, $messages, $attributes)
{
    return new CustomValidator($translator, $data, $rules, $messages, $attributes);
});

Use it (in a form request, for example): 使用它(例如,在表单请求中):

class StoreSomethingRequest extends FormRequest {
    // ...

    public function rules()
    {
        return [
            'percentage' => 'empty_if:number',
            'number'     => 'empty_if:percentage',
        ];
    }
}

Update Just tested it in Tinker: 更新刚刚在Tinker中测试过:

Validator::make(['foo' => 'foo', 'bar' => 'bar'], ['bar' => 'empty_if:foo'])->fails()
=> true
Validator::make(['foo' => '', 'bar' => 'bar'], ['bar' => 'empty_if:foo'])->fails()
=> false
Validator::make(['foo' => '', 'bar' => 'bar'], ['foo' => 'empty_if:bar'])->fails()
=> false

this can be a good solution as well:这也是一个很好的解决方案:

return [
    'video' => [
        'bail',
        function ($attribute, $value, $fail) {
            if (request()->has($attribute) === request()->filled('videourl')) {
                return $fail('Only 1 of the two is allowed');
            }
        },
        'file',
    ],
   'videourl' => [
        'bail',
        function ($attribute, $value, $fail) {
            if (request()->has($attribute) === request()->filled('video')) {
                return $fail('Only 1 of the two is allowed');
            }
        },
    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM