簡體   English   中英

覆蓋 required_without_all laravel 的單個消息

[英]Override single message for required_without_all laravel

我一直將 required_without_all 用於 laravel 中至少需要的一個字段。 這是我的規則代碼

'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',

這是我的自定義消息,它將覆蓋 laravel 生成的默認消息

'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.',

而不是向用戶顯示多行錯誤消息。 有什么方法可以將這四條消息總結為一條消息,例如

以下季節之一,租賃公司,...必須在場。

提前致謝。

有一種非常簡單的方法可以實現這一目標。 將規則應用到一個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.'
            ]);

所以......我不一定會推薦這個,但這里有一種快速而骯臟的方法來防止在多個字段上使用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>項目仍將包含“至少一個必需的”錯誤文本。 空合並?? 只是為了在分配$prevError之前foreach不會在第一個循環中中斷。

再次......我不確定我是否可以正確推薦這樣做 - 有幾個原因導致它不是最理想的。 但是,如果您需要一種快速而骯臟的方法來實現“至少其中一個”類型規則,您可能會發現它很有用。

如果您使用表單請求,您可以在您的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
}

誠然,這並不漂亮,但我似乎無法找到另一種方法。

通過添加自定義規則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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM