How add Custom Validation Rules when using Form Request Validation in Laravel 5

前端 未结 9 1154
情歌与酒
情歌与酒 2020-12-07 12:31

I am using form request validation method for validating request in laravel 5.I would like to add my own validation rule with form request validation method.My request class

9条回答
  •  时光取名叫无心
    2020-12-07 13:11

    All answers on this page will solve you the problem, but... But the only right way by the Laravel conventions is solution from Ganesh Karki

    One example:

    Let’s take an example of a form to fill in Summer Olympic Games events – so year and city. First create one form.

    Year:

    City:


    Now, let’s create a validation rule that you can enter only the year of Olympic Games. These are the conditions

    1. Games started in 1896
    2. Year can’t be bigger than current year
    3. Number should be divided by 4

    Let’s run a command:

    php artisan make:rule OlympicYear

    Laravel generates a file app/Rules/OlympicYear.php. Change that file to look like this:

    namespace App\Rules;

    use Illuminate\Contracts\Validation\Rule;

    class OlympicYear implements Rule {

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // Set condition that should be filled
        return $value >= 1896 && $value <= date('Y') && $value % 4 == 0;
    }
    
    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // Set custom error message.
        return ':attribute should be a year of Olympic Games';
    }
    

    }

    Finally, how we use this class? In controller's store() method we have this code:

    public function store(Request $request)
    {
        $this->validate($request, ['year' => new OlympicYear]);
    }
    

    If you want to create validation by Laravel conventions follow tutorial in link below. It is easy and very well explained. It helped me a lot. Link for original tutorial is here Tutorial link.

提交回复
热议问题