Search code examples
phplaravel-5.3laravel-validation

Laravel(5.3.24+) Validation: Custom Validation with Custom Error Message


Custom error message not working for custom rule, see variable $messages uniqueTeamNameForcomp.

Custom rule is fine, custom message for rule:required is fine also.

The error message that shows for the rule uniqueTeamNameForComp is "unique_team_name_for_comp" when it should be reading the error message "This name already exist for this competition".

CONTROLLER:

public function store(Request $request){

    $rules = [
        'name'      => 'required|uniqueTeamNameForComp:'.$request->compzid,
        'compz'     => 'required'
    ];

    $messages = array(
        'uniqueTeamNameForComp' => 'This name already exist for this competition',
        'required'              => 'this works'
    );

    $this->validate($request,$rules,$messages);

}

SERVICE PROVIDER:

public function boot()
{
    Validator::extend('uniqueTeamNameForComp', function ($attribute, $value, $parameters, $validator) {
        $competitionId = $parameters[0];

        return count(Tteam::where("comp_id", "=", $competitionId)->whereName($value)->get()) == 0;
    });
}

Solution

  • The output you're seeing from Laravel is actually giving you a hint. It expects the custom messages to be keyed by the validation rule in snake case, not camel case.

    $messages = array(
        'unique_team_name_for_comp' => 'This name already exist for this competition',
        'required'                  => 'this works'
    );