Is there a way to insert, in the validator message, the wrong value passed from user?
UPDATE:
For example, If the field must accept a value from "1" to "10" and you insert "200" I'd like to write:
'The :attribute must be between 1 and 10. Your value is 200.':
$validator_default_message = [
'digits_between' => 'The ":attribute" must be between :min and :max.',
];
$validator = Validator::make($phase, [
'depth' => 'digits_between:0,10',
], $validator_default_message);
if ($validator->fails()) {
$status = $validator->failed();
$errorMessage = $validator->messages()->all();
abort($status, $errorMessage);
}
And I'd like to return the message:The depth must be between 0 and 10. Your input value is 200.
Thank you.
inside Request file add :
public function messages()
{
return [
'input_name.numeric' => 'your massage'
];
}
for more info check here : https://laravel.com/docs/5.4/validation#customizing-the-error-messages
public function messages()
{
return [
'fieldname.numeric' => 'The :attribute must be numeric. Your value is '.$request->input('fieldname')
];
}
This might offer you more insight:
https://laracasts.com/discuss/channels/general-discussion/laravel-5-custom-error-messages
That messages() method can be put on here: app/Http/Requests/YourRequest.php
From #Laracasts:
Using Laravel 5 .4 and saw that the validate() method optionally accepts the messages[] as its third argument and did this.
$this->validate($request,
[
'document_date_created' => 'required',
'document' => 'required'
],
[
'document_created_at.required' => 'Sample message',
'document.required' => 'Another Sample Message'
]
);
When you have an instance of a Validator on which you used the validate() method, it will return back to the page with the old values which can be retrieved by using old('form field') i.e. old('title')
In your view you can check if you have an error message for a specific field and rule by using:
if($errors->has('input_name.numeric')){
//code
)
Here you could use the old input value to return a message:
{{$errors->get('input_name.numeric').
' Your value was ' . old('input_name') . '.'}}
This will print for example:
The input_name must be between 1 and 10. Your value was 200.
Documentation about retrieving old input can be found here.
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
so basically the rule of the game is
return [
yourFieldName.ValidationRule => Customessage
]
and $request->input('fieldname') to access the value
this is an example taken from laravel doc
Related
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 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.
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.
I am having trouble locating the error message of the Minimum Number Validation.. i tried overwriting it with this code
public function rules()
{
return [
[['login_name'], 'string', 'min' => 5, 'message' => 'Please input more than 5 characters.'],
];
}
but it did not change the default error message which is:
The login name must be at least five characters.
i wanna know where the default error message is..
and is there a way to overwrite this error message..
Thanks in advance.
Try:
public function rules()
{
return [
[['login_name'], 'string', 'min' => 5, 'tooShort' => 'Please input more than 5 characters.'],
];
}
For more details refer to this link.
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.