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

时间:2015-06-04 05:35:05

标签: php validation laravel

我有两个字段,即数字和百分比。我希望用户只在一个输入字段中输入值。如果用户在数字和百分比字段中输入值,则系统应该抛出验证错误。我们可以用laravel验证来实现这一目标吗?

感谢。

1 个答案:

答案 0 :(得分:5)

您可以为此编写自定义验证器: http://laravel.com/docs/5.0/validation#custom-validation-rules

它可能看起来像这样:

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;
    }
}

在服务提供商中注册:

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

使用它(例如,在表单请求中):

class StoreSomethingRequest extends FormRequest {
    // ...

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

<强>更新 刚刚在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