我似乎无法在Laravel 4上正确运行“required_without”验证。我有一个包含三个字段的表单。我只希望用户提交播放器或铃声,而不是同时提交两者。
当我在“tournament_player”和“tournament_ringer”文本框中输入内容时,验证成功。
查看
<h3>Add Player</h3>
{{ Form::open(array('url'=>'members/tournament/addplayer', 'action' => 'post', 'class'=>'form-horizontal')) }}
{{ form::hidden('user_id', Auth::user()->id) }}
{{ form::hidden('tournament_id', $tournament->id) }}
<div class="form-group{{ $errors->first('side2_p1', ' has-error') }}">
<label class="col-sm-2 control-label col-sm-pad">Player</label>
<div class="col-sm-5 col-sm-pad">
{{ Form::select('tournament_player', array('' => 'Choose...') + $users, 'key', array('class' => 'form-control input')) }}
{{ $errors->first('tournament_player', '<span class="help-block">:message</span>') }}
</div>
<div class="col-sm-4 col-sm-pad">
{{ Form::text('tournament_ringer', '', array('class' => 'form-control input', 'placeholder' => 'Ringer')) }}
{{ $errors->first('tournament_ringer', '<span class="help-block">:message</span>') }}
</div>
</div>
<div class="form-group">
<label for="gender" class="col-sm-2 control-label col-sm-pad">Bracket</label>
<div class="col-sm-3 col-sm-pad">
{{ Form::selectRange('player_bracket', 1, ($tournament->size/2), '1', array('class' => 'form-control input')) }}
{{ $errors->first('player_bracket', '<span class="help-block">:message</span>') }}
</div>
</div>
{{ Form::submit('Add', array('class'=>'btn btn-success')) }}
{{ Form::token() . Form::close() }}
</div>
控制器
public function postAddPlayer()
{
$validator = Validator::make(
array(
'tournament_player' => Input::get('tournament_player'),
'tournament_ringer' => Input::get('tournament_ringer')),
array(
'tournament_player' => 'required_without:tournament_ringer',
'tournament_ringer' => 'required_without:tournament_ringer'),
array(
'required_without' => 'You can only add a player OR a ringer.')
);
if ($validator->passes())
{
if(Input::has('tournament_player'))
{
$tournament = Tournamentplayers::addPlayer(Input::get('tournament_player'));
}elseif(Input::has('tournament_ringer')){
$tournament = Tournamentplayers::addRinger(Input::get('tournament_ringer'));
}
}else{
return Redirect::to('members/tournament/'.Input::get('tournament_id').'/edit')
->withErrors($validator)
->withInput()
->with('message', 'Error! Something was wrong.')
->with('status', 'danger');
}
}
答案 0 :(得分:2)
一个简单的解决方法是使用XOR语句而不是验证程序:
if (Input::get('tournament_player') XOR Input::get('tournament_ringer')) {
//Validator passes.
} else {
//Create error message and redirect with it.
}
答案 1 :(得分:1)
你的代码中有错误吗?我看到你的规则中有'tournament_ringer' => 'required_without:tournament_ringer'
- 你的意思是,required_without:tournement_player
。