Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.5 validate with custom messages

I'm working on a pw change form in my laravel app. I want to use the validator with custom error messages.

My code looks like this:

  $rules = [
    'username' => 'required|max:255',
    'oldpassword' => 'required|max:255',
    'newpassword' => 'required|min:6|max:255|alpha_num',
    'newpasswordagain' => 'required|same:newpassword',
  ];
  $messages = [
     'username.required' => Lang::get('userpasschange.usernamerequired'),
     'username.max:255' => Lang::get('userpasschange.usernamemax255'),
     'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
     'oldpassword.max:255' => Lang::get('userpasschange.oldpasswordmax255'),
     'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
     'newpassword.min:6' => Lang::get('userpasschange.newpasswordmin6'),
     'newpassword.max:255' => Lang::get('userpasschange.newpasswordmax255'),
     'newpassword.alpha_num' => Lang::get('userpasschange.newpasswordalpha_num'),
     'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
     'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
 ];

  $validator = Validator::make($request->all(), $rules, $messages);
  $validator->setCustomMessages($messages);

  Log::debug("custommessages: " . json_encode($messages));
  Log::debug("messages: " . json_encode($validator->messages()));

In the log custommessages is shows my custom msgs, but in the next line there is the original messages.

I'm working from the official doc.

Have anybody meet this problem?

Thx for the answers in advance!

like image 513
LakiGeri Avatar asked Mar 22 '18 15:03

LakiGeri


People also ask

What is the method used for specifying custom messages for validation errors in form request?

What is the method used for specifying custom message for validation errors in form request? After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session.

How can I check email is valid in laravel?

You can check if an email is valid or not in Laravel using the validate method by passing in the validation rules. You can validate your email addresses using one or more of the validation rules we have discussed.

What is custom validation in laravel?

You can make the code powerful by using the Laravel custom validation rule with parameters. This streamlines the flow between the logic and code wherever required. Laravel offers various convenient validation rules that can be applied to the data if values are specific to a database table.


2 Answers

A rewrite and the recommended way of doing it. Manual for reference https://laravel.com/docs/5.5/validation#creating-form-requests

Use requests files.

  1. run php artisan make:request UpdateUserPasswordRequest
  2. Write the request file

Edit feb 2020: in the latest version of Laravel in the authorize method the global auth() object can be used instead of \Auth so \Auth::check() will become auth()->check(). Both still work and will update if something is removed from the framework

 <?php
     
     namespace App\Http\Requests;
 
     class UpdateUserPasswordRequest extends FormRequest
     {
         /**
          * Determine if the user is authorized to make this request.
          *
          * @return bool
          */
         public function authorize()
         {
             // only allow updates if the user is logged in
             return \Auth::check();
              // In laravel 8 use Auth::check() 
             // edit you can now replace this with return auth()->check();
         }
     
         /**
          * Get the validation rules that apply to the request.
          *
          * @return array
          */
         public function rules()
         {
             return [
                 'username' => 'required|max:255',
                 'oldpassword' => 'required|max:255',
                 'newpassword' => 'required|min:6|max:255|alpha_num',
                 'newpasswordagain' => 'required|same:newpassword',
             ];
         }
     
         /**
          * Get the validation attributes that apply to the request.
          *
          * @return array
          */
         public function attributes()
         {
             return [
                 'username'            => trans('userpasschange.username'),
                 'oldpassword'             => trans('userpasschange.oldpassword'),
                 'newpassword'             => trans('userpasschange.newpassword'),
                 'newpasswordagain'       => trans('userpasschange.newpasswordagain'),
             ];
         }
     
         /**
          * Get the validation messages that apply to the request.
          *
          * @return array
          */
         public function messages()
         {
     // use trans instead on Lang 
             return [
          'username.required' => Lang::get('userpasschange.usernamerequired'),
          'oldpassword.required' => Lang::get('userpasschange.oldpasswordrequired'),
          'oldpassword.max' => Lang::get('userpasschange.oldpasswordmax255'),
          'newpassword.required' => Lang::get('userpasschange.newpasswordrequired'),
          'newpassword.min' => Lang::get('userpasschange.newpasswordmin6'),
          'newpassword.max' => Lang::get('userpasschange.newpasswordmax255'),
          'newpassword.alpha_num' =>Lang::get('userpasschange.newpasswordalpha_num'),
          'newpasswordagain.required' => Lang::get('userpasschange.newpasswordagainrequired'),
          'newpasswordagain.same:newpassword' => Lang::get('userpasschange.newpasswordagainsamenewpassword'),
           'username.max' => 'The :attribute field must  have under 255 chars',
             ];
         }
  1. In UserController
<?php namespace App\Http\Controllers;


// VALIDATION: change the requests to match your own file names if you need form validation
use App\Http\Requests\UpdateUserPasswordRequest as ChangePassRequest;
//etc

class UserCrudController extends Controller
{
public function chnagePassword(ChangePassRequest $request)
{
 // save new pass since it passed validation if we got here
}
}
like image 100
Indra Avatar answered Oct 21 '22 09:10

Indra


For Laravel 7.x, 6.x, 5.x
With the custom rule defined, you might use it in your controller validation like :

$validatedData = $request->validate([
       'f_name' => 'required|min:8',
       'l_name' => 'required',
   ],
   [
      'f_name.required'=> 'Your First Name is Required', // custom message
      'f_name.min'=> 'First Name Should be Minimum of 8 Character', // custom message
      'l_name.required'=> 'Your Last Name is Required' // custom message
   ]
);

For localization you can use :

['f_name.required'=> trans('user.your first name is required'],

Hope this helps...

like image 24
sta Avatar answered Oct 21 '22 10:10

sta