Laravel Custom Validation

May 23, 2017 | No Comments | Programming | laravel PHP validation

This is small article helper for those who need example of Laravel Custom Validation. Suppose we want ¬†validate if user entered valid youtube link in field. We won’t check it with API, just simple regex.

Validation File

Simple as it can be. Regex can be improved and added server side check if video exists.

<?php
//app/Validators/YoutubeValidator.php
namespace App\Validators;
 
class YoutubeValidator
{
    public function validate($attribute, $value, $parameters, $validator)
    {
        return (bool) preg_match('/^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/',$value);
    }
}

Modify service provider

Now we need to register our validator

<?php
//App/Providers/AppServiceProvider.php
 
namespace App\Providers;
 
use Illuminate\Support\ServiceProvider;
use Validator;
 
class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Validator::extend('youtube', 'App\Validators\YoutubeValidator@validate','Youtube link is invalid');
    }
 
    public function register() { }
}

Use it

In my case  I submit form in our controller:

<?php
//app/Http/Controllers/CommentController.php
namespace App\Http\Controllers;
 
use Input, Validator;
 
class CommentController extends Controller
{
 
    public function update()
    {
        $rules = [
            'comment' => 'required',
            'link' => 'youtube',
        ];
 
        $validator = Validator::make(Input::all(), $rules);
 
        if ($validator->fails()) {
            return redirect()
                ->back()
                ->withErrors($validator);
        } else {
            //proceed
        }
    }
}

I hope this will help in your future development.


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad

LEAVE A COMMENT