Search code examples
phplaravellaravel-7laravel-validation

Laravel Validator custom message with "sometimes" rule


This is a piece of my code, to validate a form input:

public function saveData(Request $request){
    $form_data = $request->all();

    $validation_fields = [
        'first_name' => 'required',
        'last_name' => 'required',
        'cod_fisc' => 'sometimes|required|size:16',
        'p_iva' => 'sometimes|required|between:11,13'
    ];

    $errorMsgs = [
        'first_name.required' => 'Il campo Nome è obbligatorio.',
        'last_name.required' => 'Il campo Cognome/Ragione sociale è obbligatorio.',
        'cod_fisc.required' => 'Il campo Codice Fiscale deve contenere 16 caratteri',
        'p_iva.required' => 'Il campo Partita Iva deve contenere 11 o 13 caratteri',
    ];

    $validator = Validator::make($form_data, $validation_fields, $errorMsgs);

    ....
}

The whole project is written for Italian people, so all messages must be in Italian. All works fine, but the two rules for cod_fisc and p_iva, that are binded to a "sometimes" rule, are displayed in English. My custom error messages are ignored.

Why?


Solution

  • Searching for your problem I have found this link: https://laracasts.com/discuss/channels/laravel/sometimes-validator-with-custom-message

    which contained a similar problem. The initial code was

    $v = Validator::make(
                        $request->all(),
                        [ 'first_name' => 'required|max:60'],
                        ['first_name.required' => 'First name is really required, yo']
    );
    
    $v->sometimes('last_name', 'required|in:fake', function($input){
                        return true;
    });
    

    and the solution was

    $v = Validator::make(
                        $request->all(),
                        [ 'first_name' => 'required|max:60'],
                        ['first_name.required' => 'First name is really required, yo'],
                        ['last_name.in' => 'Last name must be fake, too']
    );
    
    $v->sometimes('last_name', 'required|in:fake', function($input){
                        return true;
    });
    

    Apparently you may call the sometimes function on the result of Validator::make and pass the field name, the validator signature and a boolean function.