3

I've made a custom validator in my Laravel application, and I want to make a custom error. Ideally, this will be Your image must 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 fetch the parameters given in my error message?

1 Answer 1

4

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

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

Add replacer to your rule

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

If you are extend the Validator, you can add 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 laravel docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.