Where are Validator error messages stored in Laravel? - php

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

Related

CakePHP 3.x Validator refuses to take correct data

I'm trying to validate a POST to create a new user, Cake is refusing to accept the given data.
The Validator is set up in the following way:
$validator
->requirePresence('first_name', 'create')
->notEmpty('first_name');
$validator
->requirePresence('last_name', 'create')
->notEmpty('last_name');
$validator
->email('email')
->requirePresence('email', 'create')
->notEmpty('email');
$validator
->requirePresence('title', 'create')
->notEmpty('title');
Even tho I give it all the data it needs to succed, in the right format, right data type, when I debug using
$x = $employee->errors();
if ($x) {
debug($employee);
debug($x);
}
it still has errors with the fields mentioned above:
'first_name' => [
'_required' => 'This field is required'
],
'last_name' => [
'_required' => 'This field is required'
],
'email' => [
'_required' => 'This field is required'
],
'title' => [
'_required' => 'This field is required'
]
I didn't expect to have that problem with Cakes Validator, why does it refuse this? Also I don't know to how to debug deeper into the problem, since there's a lot of automagic happening in the Validator.
The error occures no matter if the fields are filled iwth correct data or not any at all - I couldn't find anybody on SO or somewhere else to debug this problem, so I'm asking here.
Thanks in advance
Found the error:
employee is an object and the validator didn't look into the object, but looked for the fields on the object level.
I solved it by shifting the scope into the object - resolved it :)
Beginner mistake I guess, happy to have found it.
Thanks for help!

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.

Laravel validation attributes "nice names"

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;

Categories