Mr.P
Mr.P

Reputation: 1257

Laravel 5.2 custom validation error message with parameter

I am pretty sure I am missing just something small, but damn-hell can't figure it out.. please help me guys :)

I've extended AppServiceProvider.php

public function boot()
    {
        //
        Validator::extend('ageLimit', 'App\Http\CustomValidator@validateAgeLimit');
    }

I've created new CustomValidator.php

<?php

namespace App\Http;
use DateTime;

class CustomValidator {

    public function validateAgeLimit($attribute, $value, $parameters, $validator)
    {
        $today = new DateTime(date('m/d/Y'));
        $bday  = new DateTime($value);

        $diff = $bday->diff($today);
        $first_param = $parameters[0];

        if( $diff->y >= $first_param ){              
            return true;
        }else{
          return false;
        }

    }

}

I've added new line to validation.php

/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
| 
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
'age_limit' => ':attribute -> Age must be at least :ageLimit years old.',

'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
],  

Here comes my rule:

'birth_date' => 'required|date|ageLimit:15', 

All of this works ok ... excluded the parameter :ageLimit in validation.php file ..

How can I get there the parameter 15 I am passing in rule ???

Because I am getting this message:

Birth day -> Age must be at least :ageLimit years old.

And certainly, I would like to get this:

Birth day -> Age must be at least 15 years old.

Upvotes: 0

Views: 1788

Answers (1)

Rwd
Rwd

Reputation: 35180

Below your Validator::extend(...) you could add:

Validator::replacer('ageLimit', function($message, $attribute, $rule, $parameters) {
    $ageLimit = $parameters[0];

    return str_replace(':ageLimit', $ageLimit, $message);
});

https://laravel.com/docs/5.2/validation#custom-validation-rules

Hope this helps!

Upvotes: 3

Related Questions