本文介绍了Laravel验证:仅必填,且仅一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个字段,分别是数字和百分比.我希望用户仅在一个输入字段中输入值.如果用户在数字和百分比字段中输入值,则系统应引发验证错误.我们可以通过laravel验证来做到这一点吗?
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?
谢谢.
推荐答案
您可以为此编写一个自定义验证器: http://laravel.com/docs/5.0/validation#custom-validation-rules
You can write a custom validator for that: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);
});
使用它(例如,在表单请求中):
Use it (in a form request, for example):
class StoreSomethingRequest extends FormRequest {
// ...
public function rules()
{
return [
'percentage' => 'empty_if:number',
'number' => 'empty_if:percentage',
];
}
}
更新刚刚在修补匠中对其进行了测试:
UpdateJust tested it in 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
这篇关于Laravel验证:仅必填,且仅一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!