Laravel 5 - How to add custom msgs to Validation? - php

Im trying to figure out how to quickly add error messages per field in Laravel 5. Here is what I got:
$validator = Validator::make($this->req->all(), [
'email_add' => 'required|email|max:100',
'pass' => 'required|max:20',
]);
So how do I put a message directly here for each field validated above? like "You forgot Email Address" and "Password is Required"?
(How to that without writing a mars rover program for 1 simple task. Like the usualy laravel 5 stuff of artisan make new something useless, add 2 namespaces, 3 middlewares, 5 classes, 7 functions and then finally override error messages!!)
[EDIT]
After some help from answers below and other search on stack, I found exactly what is to be done:
Add a message for the type of validations per field:
$validator = Validator::make($this->req->all(), [
'email_add' => 'required|email|max:100',
'pass' => 'required|max:20',
], [
'email_add.required' => 'The Email Address is actually required dude!',
'email_add.email' => 'The Email Address is is not a valid Email Address!'
]);
.
.
To just change the email_add into Email Address, i.e. the Attribute Name instead of writing a custom msg for every validation applied on every field:
Validator::make(....)->setAttributeNames(
[
'email_add'=>'Email Address',
'pass'=>'Password'
]);
Thanks for the help guyz.

try this its work for you
$validator = Validator::make($this->req->all(), [
'email_add' => 'required|email|max:100',
'pass' => 'required|max:20',
]);
$messages = [
'email_add.required' => 'You forgot Email Address',
'pass.required' => 'Password is Required',
];

To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.
'custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
],
https://laravel.com/docs/5.1/validation#custom-error-messages

if you want to change validation message for specific request you can put messages method within same request file like this
public function messages() {
'name.required' => 'custom message',
'email.required' => 'custom message for email',
'email.email' => 'custom message form email format'
}
Or if you want put validation message inside controller just pass third parameter as a message.

Related

Laravel Validation: Custom message as array

I'm trying to validate a regular email/password login with some basic rules:
{
$request->validate([
'email' => ['bail', 'required', 'string', 'email', 'exists:users.users,email'],
'password' => ['bail', 'required', 'string', 'password'],
], [
'email.exists' => "Email does not exist in our system"
]);
}
When displaying these errors, it's easy enough to output them below my input:
However, where the "Invalid Email" text is shown within the top right of the input, I'm trying to make that custom, and not a hardcoded string in my component. Ideally, this would also come from the error message - though I have no idea how to approach doing so. In my mind, it would look something like this, but I'm struggling to figure out how to make the Validator accept an array rather than a string. Is this possible?
'email.exists' => ["Invalid email",
"Email does not exist in our system"
]

Add a custom validation error message laravel

I can do something like this to validate something on the controller.
$this->validate($request,[
'myinput'=>'regex:some pattern'
]);
and the output of this would be something like this
The myinput format is invalid.
What i want was to show something of my own message
Only some pattern allowed
How do i achieve this on laravel?
There are many techniques to customize validator messages.
Validate inside the controller
It would be looked like this
$validate = Validator::make($request->all(), [
'name'=>'required|max:120',
'email'=>'required|email|unique:users,email,'.$id,
'password'=>'nullable|min:6|confirmed'
],
[
'name.required' => 'User name must not be empty!',
'name.max' => 'The maximun length of The User name must not exceed :max',
'name.regex' => 'Use name can not contain space',
'email.required' => 'Email must not be empty!',
'email.email' => 'Incorrect email address!',
'email.unique' => 'The email has already been used',
'password.min' => 'Password must contain at least 6 characters',
'password.confirmed' => 'Failed to confirm password'
]);
The first param is inputs to validate
The second array is validator rules
The last params is the customized validator messages
In which, the synctax is [input_variable_name].[validator_name] => "Customized message"
Second apprach: using InfyOm Laravel Generator
I like this approach the most. It provides useful tools for generating such as Controller, Models, Views, API etc.
And yet, create and update Request file. in which the Request file is using Illuminate\Foundation\Http\FormRequest where this class is extended from Illuminate\Http\Request.
It is mean that we can access Request in this file and perform validating for the incoming requests.
Here is the most interesting part to me.
The generated request file contains rules function, for example like this
public function rules() {
return [
'name' => 'required|unique:flights,name|max:20',
'airline_id' => 'nullable|numeric|digits_between:1,10',
];
}
This function actually returns the validator-rules and validate them against the inputs.
And you can override function messages from Illuminate\Foundation\Http\FormRequest to customize the error message as you need:
public function messages()
{
return [
'required' => "This field is required",
\\... etc
];
}
Nonetheless, you can do many nore with the generated request files, just refer to file in vendor folder vendor/laravel/framework/src/Illuminate/Foundation/Http from your project.
Here is the Infyom github link InfyOmLabs - laravel-generator
You can add custom validation messages to language files, like resources/lang/en/validation.php.
Another way to do that, from docs:
'custom' => [
'email' => [
'regex' => 'Please use your company email address to register. Webmail services are not permitted.'
],
'lawyer_legal_fields' => [
'number_of_areas' => 'You\'re not allowed to select so many practice areas'
],
],
You may customize the error messages used by the form request by overriding the messages method.
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
https://laravel.com/docs/5.3/validation#customizing-the-error-messages

How to return custom error message from controller method validation

How to return a custom error message using this format?
$this->validate($request, [
'thing' => 'required'
]);
to get custom error message you need to pass custom error message on third parameter,like that
$this->validate(
$request,
['thing' => 'required'],
['thing.required' => 'this is my custom error message for required']
);
For Multiple Field, Role and Field-Role Specific Message
$this->validate(
$request,
[
'uEmail' => 'required|unique:members',
'uPassword' => 'required|min:8'
],
[
'uEmail.required' => 'Please Provide Your Email Address For Better Communication, Thank You.',
'uEmail.unique' => 'Sorry, This Email Address Is Already Used By Another User. Please Try With Different One, Thank You.',
'uPassword.required' => 'Password Is Required For Your Information Safety, Thank You.',
'uPassword.min' => 'Password Length Should Be More Than 8 Character Or Digit Or Mix, Thank You.',
]
);
https://laravel.com/docs/5.3/validation#working-with-error-messages
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
"In most cases, you will probably specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file."
Strangely not present in the documentation, you can specify the first parameter as the validation rules & the second parameter as the message format directly off of the Illuminate/Http/Request instead of invoking $this or the Validator class.
public function createCustomer(Request $request)
{
# Let's assume you have a $request->input('customer') parameter POSTed.
$request->validate([
'customer.name' => 'required|max:255',
'customer.email' => 'required|email|unique:customers,email',
'customer.mobile' => 'required|unique:customers,mobile',
], [
'customer.name.required' => 'A customer name is required.',
'customer.email.required' => 'A customer email is required',
'customer.email.email' => 'Please specify a real email',
'customer.email.unique' => 'You have a customer with that email.',
'customer.mobile.required' => 'A mobile number is required.',
'customer.mobile.unique' => 'You have a customer with that mobile.',
]);
}
You need to first add following lines in view page where you want to show the Error message:
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
Here is a demo controller by which error message will appear on that page:
public function saveUser(Request $request)
{
$this->validate($request,[
'name' => 'required',
'email' => 'required|unique:users',
]);
$user=new User();
$user->name= $request->Input(['name']);
$user->email=$request->Input(['email']);
$user->save();
return redirect('getUser');
}
For details You can follow the Blog post.
Besides that you can follow laravel official doc as well Validation.

Where are Validator error messages stored in Laravel?

I have the following code in a blade file:
#if($errors->has('password_again'))
<div class="error">
* {{ $errors->first('password_again') }}
</div>
#endif
This line:
{{ $errors->first('password_again') }}
Displays:
"The password again field is required."
However I can't seem to find this string anywhere. I've looked in the Controller file which calls this blade and just went through a ton of files searching for the string and can't seem to find it. Which file should I be looking in to edit this string?
EDIT:
I tried this it doesn't seem to do anything?
$messages = [
'password_again' => 'The confirm password field is required.',
];
$validator = Validator::make(Input::all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:30|min:3|unique:users',
'password' => 'required|min:8',
'password_again' => 'required|same:password'
),
$messages
);
If needed, you may use custom error messages for validation instead of the defaults. There are several ways to specify custom messages.
Passing Custom Messages Into Validator
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);
Specifying Custom Messages In Language Files
In some cases, you may wish to specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the resources/lang/xx/validation.php language file.
Read more at:
http://laravel.com/docs/5.0/validation

How to give custom field name in laravel form validation error message

I was trying form validation in laravel.
I have a input text field in my form called 'Category' and i'm given the field name as 'cat' as short.
And i defined the validation rules like this.
public static $rules=array(
"name"=>"required|min:3",
"cat"=>"required"
);
When the validation fails i'm getting error message like this
The name field is required.
The cat field is required.
But i want to display it as "The category field is required" instead of 'cat'. How can i change 'cat' to 'Category' in error message ?.
You can specify custom error message for your field as follows.
$messages = array(
'cat.required' => 'The category field is required.',
);
$validator = Validator::make($input, $rules, $messages);
Please see Custom Error Messages section in laravel documentation for more information.
Or you can keep a mapping for your field names like below. And you can set those into you validator. So you can see descriptive name instead of real field name.
$attributeNames = array(
'name' => 'Name',
'cat' => 'Category',
);
$validator = Validator::make ( Input::all (), $rules );
$validator->setAttributeNames($attributeNames);
you can customize every message ,also change the attribute fields name in validation.php (resources/lang/en/).
for set the attribute in validation.php
'attributes' => [
'name' => 'Name',
'cat' => 'Category',
'field_name'=>'your attribute'
],
I'm using this to deal with dynamic row addition in forms. This answer is provided in context of managing larger forms.
This answer is for Laravel 5
Form request
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Response;
class SomeThingFormRequest extends Request {
public function authorize()
{
//be nice
}
public function rules()
{
//my loop building an array of rules ex: $rules['thing.attribute.'.$x]
}
public function attributes()
{
return [
'thing.attribute'.$x => 'Nice Name',
];
}
Hope this help steer you in the right direction if you are using Laravel 5. I'm currently working on testing it out. The documentation seems to be amiss regarding this potential?
I did some digging in the framework (Illuminate\Foundation\Http\FormRequest.php) and (Illuminate\Validation\Validator.php) for the clues.
Here is an Alternative
$this->validate(request(), [rules], [custom messages], [Custom attribute name]);
$this->validate(request(), [
'fname' => "required|alpha_dash|max:20",
'lname' => "required|alpha_dash|max:30",
'extensionName' => "required|alpha_dash|max:20",
'specialization' => "max:100",
'subSpecialization' => "max:100"
], [],
[
'fname' => 'First Name',
'lname' => 'Last Name',
'extensionName' => 'Extension Name',
'specialization'=> 'Specialization',
'subSpecialization'=> 'Sub Specialization'
]);
Simply got to resources/lang/en/validation.php
There is a blank array named attributes.
add your attribute name here like 'cat'=>'category'
now all validation messages show category instead of cat.
Here's an alternative:
$data = ['name' => e(Input::get('name')), 'cat' => e(Input::get('cat'))];
$rules = ['name' => 'required|min:3', 'cat' => 'required'];
// pass an item from lang array if you need to
$nice_input_names = ['cat' => trans('lang_file.a_name_for_the_category_input')];
$validator = Validator::make($data, $rules, $messages, $nice_input_names);
I think this will do it:
Validator::make($request->all(), [
"name" => "required|min:3",
"cat" => "required"
], [], [
"cat" => "category"
])->validate();
in Laravel 8 this is the Best Way to Customize Validation Attributes and Message;
$request->validate([
'cat' => "required| min:7 |max:15"
//validation Area
],
[
//customize Message
],
[
'cat' => 'Category'
//Customize Attributes Name
]);
the answer by Paul Dela Vega is big help for me, cant comment because no reputation enough.
no information of it anywhere in Laravel Docs (8.x).
maybe this is a good suggestion to laravel, to add this into their documents because it helps a lot for the beginner like me.

Categories