Laravel validation attributes "nice names" - php

I'm trying to use the validation attributes in "language > {language} > validation.php", to replace the :attribute name (input name) for a proper to read name (example: first_name > First name) . It seems very simple to use, but the validator doesn't show the "nice names".
I have this:
'attributes' => array(
'first_name' => 'voornaam'
, 'first name' => 'voornaam'
, 'firstname' => 'voornaam'
);
For showing the errors:
#if($errors->has())
<ul>
#foreach ($errors->all() as $error)
<li class="help-inline errorColor">{{ $error }}</li>
#endforeach
</ul>
#endif
And the validation in the controller:
$validation = Validator::make($input, $rules, $messages);
The $messages array:
$messages = array(
'required' => ':attribute is verplicht.'
, 'email' => ':attribute is geen geldig e-mail adres.'
, 'min' => ':attribute moet minimaal :min karakters bevatten.'
, 'numeric' => ':attribute mag alleen cijfers bevatten.'
, 'url' => ':attribute moet een valide url zijn.'
, 'unique' => ':attribute moet uniek zijn.'
, 'max' => ':attribute mag maximaal :max zijn.'
, 'mimes' => ':attribute moet een :mimes bestand zijn.'
, 'numeric' => ':attribute is geen geldig getal.'
, 'size' => ':attribute is te groot of bevat te veel karakters.'
);
Can someone tell me what i'm doing wrong. I want the :attribute name to be replaced by the "nice name" in the attributes array (language).
Thanks!
EDIT:
I noticed that the problem is I never set a default language for my Laravel projects. When I set the language to 'NL' the code above works. But, when I set my language, the language will appear in the url. And I prefer it doesn't.
So my next question: Is it possible to remove the language from the url, or set the default language so it just doesn't appear there?

Yeahh, the "nice name" attributes as you called it was a real "issue" a few month ago.
Hopefully this feature is now implemented and is very simply to use.
For simplicity i will split the two options to tackle this problem:
Global Probably the more widespread. This approach is very well explained here but basically you need to edit the application/language/XX/validation.php validation file where XX is the language you will use for the validation.
At the bottom you will see an attribute array; that will be your "nice name" attributes array. Following your example the final result will be something like this.
<!-- language: lang-php -->
'attributes' => array('first_name' => 'First Name')
Locally This is what Taylor Otwell was talking about in the issue when he says:
You may call setAttributeNames on a Validator instance now.
That's perfectly valid and if you check the source code you will see
<!-- language: lang-php -->
public function setAttributeNames(array $attributes)
{
$this->customAttributes = $attributes;
return $this;
}
**So, to use this way see the following straightforward example:**
<!-- language: lang-php -->
$niceNames = array(
'first_name' => 'First Name'
);
$validator = Validator::make(Input::all(), $rules);
$validator->setAttributeNames($niceNames);
Resources
There is a really awesome repo on Github that have a lot of languages packages ready to go. Definitely you should check it out.

The correct answer to this particular problem would be to go to your app/lang folder and edit the validation.php file at the bottom of the file there is an array called attributes:
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => array(
'username' => 'The name of the user',
'image_id' => 'The related image' // if it's a relation
),
So I believe this array was built to customise specifically these attribute names.

Since Laravel 5.2 you could...
public function validForm(\Illuminate\Http\Request $request)
{
$rules = [
'first_name' => 'max:130'
];
$niceNames = [
'first_name' => 'First Name'
];
$this->validate($request, $rules, [], $niceNames);
// correct validation

In the "attributes" array the key is the input name and the value is the string you want to show in the message.
An example if you have an input like this
<input id="first-name" name="first-name" type="text" value="">
The array (in the validation.php file) should be
'attributes' => array(
'first-name' => 'Voornaam'),
I tried the same thing and it works great. Hope this helps.
EDIT
Also I am noticing you don't pass a parameter to $errors->has() so maybe that's the problem.
To fix this check out in the controller if you have a code like this
return Redirect::route('page')->withErrors(array('register' => $validator));
then you have to pass to the has() method the "register" key (or whatever you are using) like this
#if($errors->has('register')
.... //code here
#endif
Another way to display error messages is the following one which I prefer (I use Twitter Bootstrap for the design but of course you can change those with your own design)
#if (isset($errors) and count($errors->all()) > 0)
<div class="alert alert-error">
<h4 class="alert-heading">Problem!</h4>
<ul>
#foreach ($errors->all('<li>:message</li>') as $message)
{{ $message }}
#endforeach
</ul>
</div>

In Laravel 4.1 the easy way to do this is go to the lang folder -> your language(default en) -> validation.php.
When you have this in your model, for example:
'group_id' => 'Integer|required',
'adult_id' => 'Integer|required',
And you do not want the error to be "please enter a group id", you can create "nice" validation messages by adding a custom array in validation.php.
So in our example, the custom array would look like this:
'custom' => array(
'adult_id' => array(
'required' => 'Please choose some parents!',
),
'group_id' => array(
'required' => 'Please choose a group or choose temp!',
),
),
This also works with multi-language apps, you just need to edit (create) the correct language validation file.
The default language is stored in the app/config/app.php configuration file, and is English by default.
This can be changed at any time using the App::setLocale method.
More info to both errors and languages can be found here validation and localization.

In Laravel 7.
use Illuminate\Support\Facades\Validator;
Then define niceNames
$niceNames = array(
'name' => 'Name',
);
And the last, just put $niceNames in fourth parameter, like this:
$validator = Validator::make($request->all(), $rules, $messages, $niceNames);

I use my custom language files as Input for the "nice names" like this:
$validator = Validator::make(Input::all(), $rules);
$customLanguageFile = strtolower(class_basename(get_class($this)));
// translate attributes
if(Lang::has($customLanguageFile)) {
$validator->setAttributeNames($customLanguageFile);
}

$customAttributes = [
'email' => 'email address',
];
$validator = Validator::make($input, $rules, $messages, $customAttributes);

The :attribute can only use the attribute name (first_name in your case), not nice names.
But you can define custom messages for each attribute+validation by definine messages like this:
$messages = array(
'first_name_required' => 'Please supply your first name',
'last_name_required' => 'Please supply your last name',
'email_required' => 'We need to know your e-mail address!',
'email_email' => 'Invalid e-mail address!',
);

Well, it's quite an old question but I few I should point that problem of having the language appearing at the URL can be solved by:
Changing the language and fallback_language at config/app.php;
or by setting \App::setLocale($lang)
If needed to persist it through session, I currently use the "AppServiceProvider" to do this, but, I think a middleware might be a better approach if changing the language by URL is needed, so, I do like this at my provider:
if(!Session::has('locale'))
{
$locale = MyLocaleService::whatLocaleShouldIUse();
Session::put('locale', $locale);
}
\App::setLocale(Session::get('locale'));
This way I handle the session and it don't stick at my url.
To clarify I'm currently using Laravel 5.1+ but shouldn't be a different behavior from 4.x;

Related

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.

Laravel 5 - How to add custom msgs to 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.

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