Laravel“至少一个”字段需要验证例:

2022-08-30 09:05:37

所以我有这个表格和这些字段

{{ Form::open(array('url' => 'user', 'id' => 'user_create_form')) }}

    <div class="form-input-element">
        <label for="facebook_id">ID Facebook</label>
        {{ Form::text('facebook_id', Input::old('facebook_id'), array('placeholder' => 'ID Facebook')) }}
    </div>

    <div class="form-input-element">
        <label for="twitter_id">ID Twitter</label>
        {{ Form::text('twitter_id', Input::old('twitter_id'), array('placeholder' => 'ID Twitter')) }}
    </div>

    <div class="form-input-element">
        <label for="instagram_id">ID Instagram</label>
        {{ Form::text('instagram_id', Input::old('instagram_id'), array('placeholder' => 'ID Instagram')) }}
    </div>

{{ Form::close() }}

我想告诉Laravel,这些字段中至少有一个是必需的。如何使用验证器执行此操作?

$rules = array(
    'facebook_id'                   => 'required',
    'twitter_id'                    => 'required',
    'instagram_id'                  => 'required',
);
$validator = Validator::make(Input::all(), $rules);

答案 1

尝试查看required_without_all:foo,bar,...,看起来应该为您完成。引用他们的文档:

仅当所有其他指定字段都不存在时,验证中的字段才必须存在。


例:

$rules = array(
    'facebook_id' => 'required_without_all:twitter_id,instagram_id',
    'twitter_id' => 'required_without_all:facebook_id,instagram_id',
    'instagram_id' => 'required_without_all:facebook_id,twitter_id',
);
$validator = Validator::make(Input::all(), $rules);

答案 2
**For automatic validation**

$rules = array(
    'facebook_id' => 'required_without_all:twitter_id,instagram_id',
    'twitter_id' => 'required_without_all:facebook_id,instagram_id',
    'instagram_id' => 'required_without_all:facebook_id,twitter_id',
);
$message = array(
    'facebook_id' => 'The facebook field is required when none of twitter / instagram are present.',
    'twitter_id' => 'The twitter field is required when none of facebook / instagram are present.',
    'instagram_id' => 'The instagram field is required when none of twitter / facebook are present.');

$validator = Validator::make(Input::all(), $rules, $message)->validate();

推荐