I have a validate like this :
TitleRequest.php:
public function rules()
{
return [
'title_name_report' => 'required|min:2',
'develop_code' => 'required',
];
}
public function messages()
{
return [
'title_name_report.required',
'title_name_report.min',
'develop_code.required'
];
}
Lang/vi/validation.php.
'title_name_report.required'=>"Please enter, :attribute !",
'title_name_report.min'=>"Min length is :attribute",
'develop_code.required'=>"Please enter :attribute !",
'custom' => [
'attribute-name' => [
'rule-name' => 'custom-message',
],
],
'attributes' => [],
views/title.blade.php
<input type="text" class="form-control" id="title_name_report" name="title_name_report"
value="{{old('title_name_report')}}">
#if($errors->has('title_name_report'))
<div class="error-text">
{{$errors->first('title_name_report')}}
</div>
#endif
I have 2 question :
1. How can I display exactly errors message, I have 2 rules but it always display the first rule's message. When I try enter 1 character it still display required message.
2. How can I use the langs file so I dont need put message into request files.
Please help me, thank so much !
You can show all validation errors with this :
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Put custom validation messages in resources/lang/xx/validation.php file in this format :
'custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
],
More Info : https://laravel.com/docs/5.4/validation#custom-error-messages
How can I display exactly errors message, I have 2 rules but it always display the first rule's message. When I try enter 1 character it still display required message.
Laravel will only validate your input in order. It will not return an
error message of the next rules until it didn't pass the first one.
How can I use the langs file so I dont need put message into request files.
You can find to localization details here. It is under
/resources/lang/en/validation.php
If you want to change the validation message tru Request file, You should do it like this
public function messages()
{
return [
'title_name_report.required' => "Title is required.",
'title_name_report.min' => "Title should not less than 2.",
'develop_code.required' => "Code is required.",
];
}
Related
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
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.
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
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;