代码之家  ›  专栏  ›  技术社区  ›  Bibek Shakya Dev. Joel

覆盖所需的单个消息,而不覆盖所有laravel

  •  1
  • Bibek Shakya Dev. Joel  · 技术社区  · 6 年前

    这是我的规则代码

    'rental_company_id'         => 'required_without_all:camper_id,take_over_station_id,returnable_station_id',
    'camper_id'                 => 'required_without_all:rental_company_id,take_over_station_id,returnable_station_id',
    'take_over_station_id'      => 'required_without_all:rental_company_id,camper_id,returnable_station_id',
    'returnable_station_id'     => 'required_without_all:rental_company_id,camper_id,take_over_station_id',
    

    'rental_company_id.required_without_all'                => 'The Rental Companies is required when none of Campers, Takeover stations and Returnable stations are present.',
    'camper_id.required_without_all'                        => 'The Campers is required when none of Rental Companies, Takeover stations and Returnable stations are present.',
    'take_over_station_id.required_without_all'             => 'The Takeover stations is required when none of Campers, Rental Companies and Returnable stations are present.',
    'returnable_station_id.required_without_all'            => 'The Returnable stations is required when none of Campers, Rental Companies and Takeover stations are present.',
    

    而不是向用户显示多行错误消息。有没有办法把这四条信息总结成一条信息,比如

    接下来的一个季度,租赁公司,。。。必须在场。

    提前谢谢。

    2 回复  |  直到 6 年前
        1
  •  3
  •   SASM    4 年前

    有一个非常简单的方法可以实现这一点。将规则应用于虚构的 ids 字段,然后包括要在其之后应用验证的所有实际字段 required_without_all . 只有一条对应的验证消息。

    $validator = Validator::make($request->all(), [
                'ids' => 'required_without_all:rental_company_id,camper_id,take_over_station_id, returnable_station_id'
                ], [
                'required_without_all' => 'One of the following Season,Rental companies,... must be present.'
                ]);
    
        2
  •  2
  •   Axionatic    3 年前

    所以我不一定推荐这样做,但这里有一个快速而肮脏的方法来防止在使用时出现重复的错误消息 required_without_all

    1. 在控制器中,为字段提供自定义设置 错误消息(即不使用 :attribute
    public function foo(Request $request)
    {
        $request->validate(
            [
                // the "at least one of these" fields must be grouped together here.
                'field_1' => 'required_without_all:field_2|nullable|etc',
                'field_2' => 'required_without_all:field_1|nullable|etc',
                // etc...
            ],
            [
                'field_1.required_without_all' => 'At least one is required',
                'field_2.required_without_all' => 'At least one is required',
                // etc...
                // If this list of fields is the only time you're using
                // required_without_all, you can just use a single catch-all
                // ['required_without_all' => 'message'] instead
            ]
        );
    }
    
    1. 然后,在您的视图中,在循环/写入错误消息时检查重复的错误消息:
    @if ($errors->any())
        <ul>
            @foreach ($errors->all() as $error)
                @if ($error !== ($prevError ?? ''))
                    <li>{{ $prevError = $error }}</li>
                @endif
            @endforeach
        </ul>
    @endif
    

    PHP的一个怪癖(?)是它在变量赋值时返回赋值,这就是我们的 <li> ?? 就是这样 foreach 在第一个循环中没有中断,之前 $prevError 已经分配了。

        3
  •  1
  •   Mozammil    6 年前

    如果您使用的是表单请求,您可以在 messages()

    return [
        'required_without_all' => 'One of the field must be present.'
    ];
    

    如果您使用的是手动验证器,则可以执行以下操作:

    $messages = [
        'required_without_all' => 'One of the field must be present.',
    ];
    
    $validator = Validator::make($input, $rules, $messages);
    

    编辑 :另一种方法是检查MessageBag是否包含这些字段之一的错误,然后在视图中相应地显示另一个字段。例如:

    @if (
        $errors->has('rental_company_id')
        || $errors->has('camper_id')
        || $errors->has('take_over_station_id') 
        || $errors->has('returnable_station_id')
    ) {
        // display the error message you need
    }
    

    诚然,这并不漂亮,但我似乎找不到另一种方法。

        4
  •  1
  •   Shiro    4 年前

    php artisan make:rule AssignDataValidation

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $isSet = false;
        $input = Input::all();
        foreach (Discount::ASSIGNED_DATA_FIELD as $data){
            if (isset($input[$data])){
                $isSet = true;
                break;
            }
        }
        return $isSet;
    }
    
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'One of the following Season, Rental companies,... must be present.';
    }
    

    根据表格要求,我有一个覆盖 getValidatorInstance() 方法并在验证后调用以手动添加我的规则,并在具有自定义名称的错误包上触发

    protected function getValidatorInstance()
    {
        $validator = parent::getValidatorInstance();
        $validator -> after(function ($validator){
            $timeDataValidation     = new TimeDataValidation;
            $assignDataValidation   = new AssignDataValidation;
            if (!$timeDataValidation -> passes(TimeDataValidation::FIELD,Discount::TIME_DATA_FIELD)){
                $validator -> errors() -> add(TimeDataValidation::FIELD,$timeDataValidation -> message());
            }
            if (!$assignDataValidation -> passes(AssignDataValidation::FIELD,Discount::ASSIGNED_DATA_FIELD)){
                $validator -> errors() -> add(AssignDataValidation::FIELD,$assignDataValidation -> message());
            }
        });
        
        return $validator;
    }