Home > Software engineering >  How to add a custom Laravel error message when using Rule::in as validation
How to add a custom Laravel error message when using Rule::in as validation

Time:11-27

I am validating a select dropdown in Laravel with an array of agency names. I am using Rule::in() to do this. The validation works well and I am getting the standard error message back 'The selected agency-name is invalid'. I want to edit this into a custom error message but am having difficulty doing this the same way as I have before. Here is my code.

$agencies = Session::get('config.agency-names');
    $agency_names = array();
    for ($x = 0; $x < count($agencies['Agencies']); $x  ) {
        $name = $agencies['Agencies'][$x]["AgencyName"];
        array_push($agency_names, $name);
        array_push($agency_names, '');
    }

$request->validate([
        'referral'    => 'required',
        'agency-name' => ['required_if:referral,no', Rule::in($agency_names)],
        'password'    => 'required|min:6|regex:/[A-Z]/|regex:/[a-z]/|regex:/[0-9]/|confirmed'], [
        // New custom agency name message
        agency-name.Rule::in(agency_names) => 'NEW MESSAGE (DOESN\'T WORK)',
        // Custom password messages.
        'password.confirmed' => 'Confirmation password did not match, please try again.',
        'password.regex'     => 'Password does not meet criteria, Please try again.',
        'password.min'       => 'Password does not meet criteria, please try again.',
]);

CodePudding user response:

in validate method, you have two parameters, one for the fields input and the other for validation messages.

validation messages are called according to the validation rules with validation type, using Rule object doesn't change that.

in your code you had to add 'agency-name.in' just like when you use in validation

$request->validate([
        'referral'    => 'required',
        'agency-name' => ['required_if:referral,no', Rule::in($agency_names)],
        'password'    => 'required|min:6|regex:/[A-Z]/|regex:/[a-z]/|regex:/[0-9]/|confirmed'], [
        // New custom agency name message
       'agency-name.in' => 'NEW MESSAGE ',
        // Custom password messages.
        'password.confirmed' => 'Confirmation password did not match, please try again.',
        'password.regex'     => 'Password does not meet criteria, Please try again.',
        'password.min'       => 'Password does not meet criteria, please try again.',
]);
  • Related