我在使用required_unless
验证时遇到问题。
我想做的是说,当building name
为空或以其他方式循环时,需要building number
,所以当building number
为空时,需要building name
。目前,这两者都需要。
public function rules(Request $request)
{
$id = $request->input('entity_id');
$entity = Entity::with('address')
->find($id);
$validation = $entity->id;
return [
'name' => 'required|alpha_special|unique:entities,name,'.$validation.'|min:3|max:30',
'type' => 'required',
'email' => 'required|email|unique:entities,email,'.$validation,
'building_name' => 'alpha|required_unless:building_number,value',
'building_number' => 'numeric|required_unless:building_name,value',
'street' => 'required|alpha_spaces',
'town' => 'nullable|alpha',
'city' => 'nullable|alpha',
'postcode' => 'required|max:8',
'telephone' => 'required|telephone',
'ical' => 'nullable|active_url',
];
}
视图:
<div class="hidden multi form-group{{ $errors->has('building_name') ? ' has-error' : '' }}">
<div class="building_name_message form-control alert-warning" style="display: none;"></div>
<label id="building_name_label" for="building_name" >Building Name</label>
<input id="building_name" type="text" class="form-field form-control" placeholder="Building name (If applicable)" name="building_name" value="{{ old('building_name') }}">
@if ($errors->has('building_name'))
<span class="help-block">
<strong>{{ $errors->first('building_name') }}</strong>
</span>
@endif
<div class="building_number_message form-control alert-warning" style="display: none;"></div>
<label id="building_number_label" for="building_number" >Building Number</label>
<input id="building_number" type="text" class="form-field form-control" placeholder="Building Number (If applicable)" name="building_number" value="{{ old('building_number') }}">
@if ($errors->has('building_number'))
<span class="help-block">
<strong>{{ $errors->first('building_number') }}</strong>
</span>
@endif
<div class="form-navigation">
<button type="button" class="previous btn btn-info pull-left">< Previous</button>
<button type="button" id="next" class="next btn btn-info pull-right">Next ></button>
</div>
</div>
最佳答案
您必须在验证空值时放置null而不是value。
'building_name' => 'alpha|required_unless:building_number,null',
'building_number' => 'numeric|required_unless:building_name,null',
另一种方法是将
required_without
用作:'building_name' => 'alpha|required_without:building_number',
'building_number' => 'numeric|required_without:building_name',
参见文档here
更新
由于上述验证分别检查
alpha
和numeric
的building_name
和building_number
类型,因此您可以更改验证规则的顺序,以便它首先检查required_without
而不检查值。不存在。'building_name' => 'required_without:building_number|alpha',
'building_number' => 'required_without:building_name|numeric',
这可能适用于您的情况。
希望你能理解。
关于laravel - Laravel required_除非验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45209014/