Custom Validation Error Options

I made a custom validator in my Laravel application and I want to make a custom error. Ideally, your image should be at least 500 by 500 pixels.

However, I cannot figure out how to get the parameters (500, 500) in the validation.php file.

This is the current error message:

"image_dimensions" => "Your :attribute must be at least GET PARAMETERS HERE",

      

Here's the validator:

Validator::extend('image_dimensions', function($attribute, $value, $parameters) {

    $image = Image::make($value);

    $min_width = $parameters[0];
    $min_height = $parameters[1];

    if ($image->getWidth() < $min_width) {
        return false;
    } else if ($image->getHeight() < $min_height) {
        return false;
    }

    return true;

});

      

And here I am using it:

$validator = Validator::make(
    array(
        'image' => Input::file('file'),
    ),
    array(
        'image' => 'image_dimensions:500,500'
    )
);

      

How do I get the parameters listed in my error message?

+3


source to share


1 answer


Add replacements to your message, for example: myMin and: myMax

"image_dimensions" => "Your :attribute must be at least :myMin to :myMax",

      

Add a replacement to your rule

Validator::replacer('image_dimensions', function($message, $attribute, $rule, $parameters)
{
    return str_replace(array(':myMin', ':myMax'), $parameters, $message);
});

      



If you are extending Validator, you can add a replace method for your rule:

class CustomValidator extends Illuminate\Validation\Validator {

    public function validateFoo($attribute, $value, $parameters)
    {
        return $value == 'foo';
    }

    protected function replaceFoo($message, $attribute, $rule, $parameters)
    {
        return str_replace(':foo', $parameters[0], $message);
    }

}

      

For more information read the laravel docs

+3


source







All Articles