How does laravel validator pass value to the variables(like :min) in validation error messages?

StackOverflow https://stackoverflow.com/questions/23607338

  •  20-07-2023
  •  | 
  •  

Question

I added a custom validation and it's working properly except the custom error message.

My custom validator:

public function getLength($value) {

    return (strlen($value) + mb_strlen($value, 'utf8'))/2;

}

public function validateLengthMin($attribute, $value, $parameters) {

    return $this->getLength($value) >= $parameters[0];

}

My custom error message:

'custom' => array(

    'username' => array(

          'length_min' => 'The :attribute must be at least :min characters.',

    )
)

The error message I got is: The username must be at least :min characters. What I wish to get is the minimum length I put in the validation (i.e. lengthMin:6, and I get 6 instead of :min) .

Another question is I wish to make the error message works for all inputs rather than only username. Therefore I tried this:

'custom' => array(

     "length_min" => "The :attribute must be at least :min characters.",

)

but it didn't work.

Thanks.

Was it helpful?

Solution

As in documentation here

When creating a custom validation rule, you may sometimes need to define custom place-holder replacements for error messages. You may do so by creating a custom Validator as described above, and adding a replaceXXX function to the validator.

Then you have to create replacer function inside your custom validator class like this

protected function replaceLengthMin($message, $attribute, $rule, $parameters)
{
    return str_replace(':min', $parameters[0], $message);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top