簡體   English   中英

Laravel 5.1中的自定義驗證替換程序

[英]Custom Validation Replacers in Laravel 5.1

我正在嘗試在Laravel 5.1應用程序中創建自定義驗證替換器。

我現在有

Validator::replacer('year', 'App\CustomValidators@replaceYear');

在我的AppServiceProvider文件中,相應的生活在我的自定義類中。 但是,當我在驗證消息中包含:year時,它不會被替換。 我錯過了什么?

這是我的替換功能。

public function replaceYear($message, $attribute, $rule, $parameters)
{
    return str_replace([':year'], $parameters, $message);
}

我真正應該做的是設置我的替換器類似於:

Validator::replacer('dateInYear', 'App\CustomValidators@replaceDateInYear');

dateInYear名稱與我設置的自定義驗證規則的名稱相對應。 然而,我最終做的是擴展驗證器類,因此我不再需要聲明每個自定義規則和替換器。 我的驗證器類現在看起來像這樣:

<?php

namespace App\Services;

use Carbon\Carbon;
use \Illuminate\Validation\Validator;

class CustomValidator extends Validator
{

    /**
     * The new validation rule I want to apply to a field. In this instance,
     * I want to check if a submitted date is within a specific year
     */
    protected function validateDateInYear($attribute, $value, $parameters, $validator)
    {
        $date = Carbon::createFromFormat('m/d/Y', $value)->startOfDay();

        if ($date->year == $parameters[0]) {
            return true;
        }
        return false;
    }

    //Custom Replacers
    /**
     * The replacer that goes with my specific custom validator. They
     * should be named the same with a different prefix word so laravel
     * knows they should be run together.
     */
    protected function replaceDateInYear($message, $attribute, $rule, $parameters)
    {
        //All custom placeholders that live in the message for
        //this rule should live in the first parameter of str_replace
        return str_replace([':year'], $parameters, $message);
    }
}

這讓我可以單獨留下我的AppServiceProvider文件,只需要注冊新的驗證類,我真的可以在任何服務提供商中做。

Laravel的文檔特別缺乏替換者需要發生的事情,所以我希望這可以幫助有人在路上。

暫無
暫無

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

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