【问题标题】:Minimum 1 field is required from 26 field in laravel validationlaravel 验证中的 26 个字段中至少需要 1 个字段
【发布时间】:2020-08-20 12:41:20
【问题描述】:

我想用 laravel 做收据。我有 26 个输入字段。很难用条件来一一声明验证。是否可以要求至少 1 个字段?请帮忙。

【问题讨论】:

    标签: php laravel validation


    【解决方案1】:
    $rules = [
        'a_field' => 'required_without_all:b_field,c_field',
        'b_field' => 'required_without_all:a_field,c_field',
        'c_field' => 'required_without_all:a_field,b_field',
    ];
    $message = [
        'a_field' => 'The a is required when none of other fields are present.',
        'b_field' => 'The b is required when none of other fields are present.',
        'c_field' => 'The c is required when none of other fields are present.',
    ];
    

    输入太多

    $fields = collect(['a', 'b', 'c', 'd', 'e']);
    
    $rules = $fields->mapWithKeys(function ($field) use ($fields) {
        return [
            $field => 'required_without_all:' . $fields->reject(function ($item) use ($field) {
                return $item == $field;
            })->implode(',')
        ];
    })->toArray();
    

    【讨论】:

    • 我需要为这个验证添加 26 行吗?还有其他最短的方法吗?喜欢使用数组或其他任何东西?
    • 这对你有帮助吗?
    • 我不知道 desine 自定义规则.. 你能给我在验证中定义这个方法的方法吗?请问?
    • 这不是自定义规则
    • 我一直使用这个代码...$this->validate($request, [ 'field' => 'required', ]);
    猜你喜欢
    • 2014-06-17
    • 2017-06-02
    • 2011-07-21
    • 2016-06-29
    • 1970-01-01
    • 2023-03-10
    • 2022-12-08
    • 1970-01-01
    • 2017-07-05
    相关资源
    最近更新 更多