I'm using the following code in my controller action for validation. I'm 100% sure this is the code that's being used for the validation as removing and adding validations is working as expected:
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
], [
'email.required' => 'Vul een e-mailadres in.',
'email.email' => 'Vul een geldig e-mailadres in.',
'password.required' => 'Vul een wachtwoord in.'
]);
The problem is that it keeps showing the default error messages ("The email field is required.") instead of the messages I'm providing ("Vul een e-mailadres in.").
I'm using the following code to display the errors in the view:
{{ $errors->first('email') }}
I guess this is the right way to do this, because when I choose Go To Declaration of the validate method in PhpStorm I see the following function:
vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:
public function validate(Request $request, array $rules, array $messages = array())
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);
if ($validator->fails())
{
$this->throwValidationException($request, $validator);
}
}
Why does it keep displaying the default error messages?
The problem is, that controller validation uses ValidatesRequests and validate method is defined this way:
public function validate(Request $request, array $rules)
{
$validator = $this->getValidationFactory()->make($request->all(), $rules);
if ($validator->fails())
{
$this->throwValidationException($request, $validator);
}
}
You cannot pass here translation. However in your case you should just create validation.php file with your translation in resources/lang/nl directory and in your config/app.php file set locale to nl
EDIT
I've looked at source and in newer Laravel 5 version, indeed 3rd parameter is used. It seems that new parameter was added and you have old version in compiled file (maybe you have modified composer.json or old composer.json file).
Whenever you have similiar issues you should run in your console:
php artisan clear-compiled
to remove compiled files.
If you don't want to have this file when development, you could remove it from composer.json file - you should remove lines with "php artisan optimize" however it will affect app performance if you don't restore it and generated new compiled.php mfile when running in production.
You can use the Validato::make() method.
$data = Input::all();
$rules = array(
'email' => 'required|email',
'password' => 'required'
);
$messages = array(
'email.required' => 'Vul een e-mailadres in.',
'email.email' => 'Vul een geldig e-mailadres in.',
'password.required' => 'Vul een wachtwoord in.'
);
$validator = Validator::make($data, $rules, $messages);
if ($validator->fails())
{
return Response::json(['error' => $validator->errors()->first()]);
}
Related
When using the validation like below with custom messages how is possible to check if the validation fails?
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$this->validate($request, $rules, $customMessages);
Like below, without custom messages is possible to use $validator->fails() but in the above case how to verify if the validation fails?
$validator = Validator::make($request->all(), [
//...
]);
if ($validator->fails()) {
//...
}
When you use $this->validate it validate your request against your validation rules and if failed then it redirect to previous page with validation message. If you want to use $validator->fails() then use Validator::make with custom message. Like this
$rules = [
'email' => 'required|email'
];
$customMessages = [
'email.required' => 'The email is required.',
'email.email' => 'Please insert a valid email.'
];
$validator = Validator::make($request->all(), $rules, $customMessages);
if ($validator->fails()) {
//...
}
Check validator make method https://laravel.com/api/5.0/Illuminate/Validation/Factory.html#method_make
much simpler solution is to use custom handler in app\Exceptions\Handler.php:
public function register()
{
$this->renderable(function (ValidationException $e, $request) {
//list of specific failed tests
$e->validator->failed();
return response()->json(['message' => 'custom message','meow'=>'meow',$e->status);
});
}
this way you keep old behavior AND can still change messages sent back to the user/frontend
I am using the following validation in the controller:
$request->validate([
'name' => [
'required',
'max:50',
Rule::unique('center_classes')
]
]);
I also tried the following:
$request->validate([
'name' => [
'required',
'max:50',
Rule::unique('center_classes', 'The class name exist.')
]
]);
I have the following line in the validation.php:
'unique' => 'The :attribute has already been taken.',
The rest of errors are working properly but Rule->unique() is the only one which causes Error Server instead of passing message.
[HTTP/1.1 500 Internal Server Error 287ms]
You need to send validation error manually into your code like this
//use first
use Validator;
$response = array('response' => '', 'success'=>false);
$rules = array('name' => 'unique:center_classes,name');
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$response['response'] = $validator->messages();
}else{
//process the request
}
return response()->json($response);
$id = $request->id;
$validation = Validator::make($request->all(), [
'email' => 'unique:customers,email,'.$request->id
]);
You're using a custom validator. You need to handle the validation failure manually. Also your code checks for unique email in the table customers except for the email of the user $request->id. I assume this is intended.
$validator = \Validator::make($request->all(), [
'email' => 'email|unique:customers,email,' . $request->id
]);
if ($validator->fails()) {
// Handle failure
}
The code below will automatically handle validation failure and redirect back with errors and inputs.
$this->validate($request, [
'email' => 'email|unique:customers,email,' . $request->id
]);
You can try something like
Validator::make($data, [
'email' => [
'required',
Rule::unique('customers')->ignore($customer->id),
],
]);
I use Laravel 5.1, I want to return translated validation error in this request class. Please any help how to return translated data.
class ContactRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
'g-recaptcha-response' => 'required|captcha',
'email' => 'required|email',
'message' => 'required',
'phone' => 'required'
];
}
}
In the resources/lang/en folder, there is a file named validation.php. Put the translated error messages in the file as described in the laravel documentation.
How your ru/validation.php file should look (but with russian text):
return [
'required' => ':attribute is required',
'email' => 'You need to enter a valid :attribute',
'captcha' => 'This :attribute is invalid'
]
First install this package : laravel langs
(Copy languages folders you wish integrate into resources/lang)
Change locale variable in config/app to 'ru' for example, and that's all :)
I want to insert my validation custom messages inside the validate function as shown:
public function postLogin(Request $request)
{
$rulesemail=['required'=>'Este campo es requerido.'];
$rulespassword=['min'=>'Debe teclear al menos :min caracteres','required'=>'Favor de teclear su contraseƱa'];
$this->validate($request, [
'email' => 'required|email|max:60', 'password' => 'required|min:6'],$rulespassword
);
But i can't get it to work. Any ideas?
You can't with the default validate() from the ValidatesRequests trait.
However you can override the function in your base controller to change that:
public function validate(Request $request, array $rules, array $messages = array())
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);
if ($validator->fails())
{
$this->throwValidationException($request, $validator);
}
}
And then simply pass the custom messages as third parameter:
$rulesemail=['required'=>'Este campo es requerido.'];
$messages=['min'=>'Debe teclear al menos :min caracteres','required'=>'Favor de teclear su contraseƱa'];
$this->validate($request, [
'email' => 'required|email|max:60',
'password' => 'required|min:6'
], $messages);
Remember that you can also globally define validation messages in a language file. This file is usually located at resources/lang/xx/validation.php
The validate() method accepts 3 parameters:
Request $request, [$errors], [$messages]
Here's an example of how to customise the error message for a validation condition:
$this->validate(
$request,
[
'first_name'=> 'required',
'last_name'=> 'required',
'email' => 'email',
'date_of_birth' => 'date_format:"Y-m-d"'
],
[
'date_format' => 'DOB'
]
);
PHPStorm provides useful tooltip to instantly see the method options.