Monday, December 9, 2013

Create Custom Validation with namespace using Laravel 4 (Part 1)

In Laravel 4, there are multiple ways on how to validate your submitted data. The built-in functionality was pretty much complete for your common validation needs. But what if you want something more, something more specific. Today, I'm going to talk about how to setup your Laravel application to cater custom validation.

But, first of all you have to have Laravel 4 installed in your system, if you haven't you can refer here in my previous blog post as a guide.

In Laravel 4 there are multiple ways to add your own validation rules, one of which is to extend the Validation Class, now this can be done without Namespaces but as using Namespaces will be less likely to cause naming collisions in the future, we’ll do it with Namespaces.

Setup my space

Start by picking a namespace, for this example, I'll call it MyCustomValidation. Next, create a folder and files wherein will place your validation files. I made "lib/MyCustomValidation" folder. Take note that it is on the same level of "app" folder and "lib" can be any folder name you want.

Next we need to add the Namespace mapping to Composer, we can do this by updating your composer.json file like:

     "autoload": {
        "psr-0": { 
          "MyCustomValidation": "lib/"

then run composer dump-autoload, this will update the autoload mappings. Now, let's proceed to our first validation!

Validation the Easy Way

The first way of extending the Validation capabilities of Laravel 4 via Classes is best suited if you only need a few extra Validation rules. Let’s start by creating the Validation Class, the example will demonstrate how to do this and we’ll keep the validation rule simple by checking if a number is divisible by 2.

Create a folder names "Validator" under "lib/MyCustomValidation". After this, let's create a class, I'll call it Text.php. Now, we will fill it up with details. (You may just copy paste). Take note that the word "validate" is required as a pre-text before your real function name.

    namespace MyCustomValidation\Validator;   

    class Text
        public function validateDivisibleByTwo($attribute, $value, $parameters)
            return ($value % 2) === 0;

Once this is done we need to register this new Validator method, this can be done by calling the following:

// Extend Validator
Validator::extend('divisible_by_two', '\MyCustomValidation\Validator\Text@divisibleByTwo');   

This can be called anywhere as long as it’s before the use of the Validation rule.

Now, we're done registering! Let's try it out! To make it easy, we'll just create a route to test it out.

    Route::get('divisibleByTwo/{number}', function($number)
        Validator::extend('divisible_by_two', '\MyCustomValidation\Validator\Text@divisibleByTwo');

        $input      = ['number' => $number];
        $rule       = ['number' => 'divisible_by_two'];
        $messages   = ['divisible_by_two' => 'The :attribute must be divisible by two.'];

        $validator = Validator::make($input, $rule, $messages);

        if ($validator->fails()) {
            return $validator->messages()->first('number');

        return $number . ' is divisible by two.';
Now when you call the route: divisibleByTwo/2, it will output an error message or if it’s divisible by 2 a success message.

Global Error Message

To further clean up our application and keep it DRY, we can set the error message at app/lang/en/validation.php,  and just add the following line in that file:

'divisible_by_two' => 'The :attribute must be divisible by two.',

And there you go, you can just call it and use your custom validation as needed. If you want to further extend and add more validation rules, click here to see part 2 of this series.

No comments:

Post a Comment