In Laravel 5.1 Project
I'm getting this Ajax Response As Error
{"errors":["The Address Name field is required.","The Recipient field is required.","The Address field is required."]}
If it is not an Ajax Response in Validation we are using has method to determine which field has mistake.
As you see there exists 3 fields has errors. I'm using twitter-bootstrap and i want to show these errors like in image
How can i reach field names ? I need a has method like in normal requests.
The easiest way is to leverage the MessageBag object of the validator. It gives back the field names on the key. This can be done like this:
// Setup the validator
$rules = array('email' => 'required|email', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
// Validate the input and return correct response
if ($validator->fails())
{
return Response::json(array(
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
), 400); // 400 being the HTTP code for an invalid request.
}
return Response::json(array('success' => true), 200);
This would give you a JSON response like this:
{
"success": false,
"errors": {
"email": [
"The E-mail field is required."
],
"password": [
"The Password field is required."
]
}
}
Related
hi folks I'm working on Laravel 5.5 and here I need to display validation messages for my API upto now I have done like this
$validator = Validator::make($request->all(),[
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
if($validator->fails)
{
$this->setMeta('status', AppConstant::STATUS_FAIL);
$this->setMeta('message', $validator->messages()->first());
return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
}
Since Laravel 5.5 has some awesome validation features I am looking to validate my request like this
request()->validate([
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
But I am facing issue here what should I do to check if the validation fails? Like I was doing by if($validator->fails)
In Laravel 5.5, like the documentation mention, the validation process is very easy :
Displaying The Validation Errors :
So, what if the incoming request parameters do not pass the given
validation rules? As mentioned previously, Laravel will automatically
redirect the user back to their previous location. In addition, all of
the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error
messages to the view in our GET route. This is because Laravel will
check for errors in the session data, and automatically bind them to
the view if they are available.
AJAX Requests & Validation :
In this example, we used a traditional form to send data to the
application. However, many applications use AJAX requests. When using
the validate method during an AJAX request, Laravel will not generate
a redirect response. Instead, Laravel generates a JSON response
containing all of the validation errors. This JSON response will be
sent with a 422 HTTP status code.
So as you said : that means you don't need to put your ifs to handle validation laravel will take care of them itself great :)
here is some syntax that i use
public static $user_rule = array(
'user_id' => 'required',
'token' => 'required',
);
public static function user($data)
{
try{
$rules = User::$user_rule;
$validation = validator::make($data,$rules);
if($validation->passes())
{
}
else
{
return Response::json(array('success' => 0, 'msg'=> $validation->getMessageBag()->first()),200);
}
return 1;
}
catch(\Illuminate\Databas\QueryException $e) {
return Response::json(array('success' => 0, 'msg' => $e->getMessage()),200);
}
}
hope this will help you!
Please add Accept: application/json in you header.
Laravel automatically send an error message with response code.
As per 2019 Laravel 5.8 it is as easy as this:
// create the validator and make a validation here...
if ($validator->fails()) {
$fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}
You will get the array of arrays of the fields' names and error messages.
You can show first error.
if ($validator->fails()) {
$error = $validator->errors()->first();
}
For all error :
$validator->errors()
I'am using Laravel on server side. Let's imagine our controller receive two fields url [string] and data [array with index head]. We can validate data and customize errors messages with
$this->validate($request, [
'url' => 'required',
'data.head' => 'required',
], [
'url.required' => 'The :attribute field is required',
'data.head.required' => 'The :attribute field is required',
]);
If validation fails, Laravel send back response with json data
{
"url": ["The url field is required"],
"data.head": ["The data.head field is required"]
}
How we can convert response data to send json, as below?
{
"url": ["The url field is required"],
"data": {
"head": ["The data.head field is required"]
}
}
In javascript
Loop on errors
error: function (errors) {
$.each(errors['responseJSON']['errors'], function (index, error) {
var object = {};
element = dotToArray(index);
object[index] = error[0];
validator.showErrors(object);
});
}
convert in dot notation into array notation. i.e abc.1.xyz into abc[1][xyz]
function dotToArray(str) {
var output = '';
var chucks = str.split('.');
if(chucks.length > 1){
for(i = 0; i < chucks.length; i++){
if(i == 0){
output = chucks[i];
}else{
output += '['+chucks[i]+']';
}
}
}else{
output = chucks[0];
}
return output
}
Laravel has an helper called array_set that transform a dot based notation to array.
I don't know how you send the errors via ajax, but you should be able to do something like that:
$errors = [];
foreach ($validator->errors()->all() as $key => $value) {
array_set($errors, $key, $value);
}
Edit:
But apparently, you should be able to not use the dot notation by Specifying Custom Messages In Language Files like this example:
'custom' => [
'email' => [
'required' => 'We need to know your e-mail address!',
],
],
I don't know if it's still a valid question but to create a custom validation using dot notation in laravel, you can specify the array like this in your validation.php
'custom' => [
'parent' => [
'children' => [
'required' => 'custom message here'
]
]
This will be the parent.children property.
see ya.
key = key.replace(/\./g, '[') + Array(key.split('.').length).join(']');
I have a custom error message that get sent back to the user if the form validation does not pass, like this:
$validator = Validator::make($request->all(), [
'name' => 'required'
]);
if ($validator->fails())
{
return response()->json([
'success' => false,
'data' => [
'errors' => $validator->messages()
],
], 400);
}
I'm just wondering what the correct error response code is for invalid form data. Currently I have it set to 400, but I don't know if this is right.
According to the laravel docs, ... a HTTP response with a 422 status code will be returned to the user ....
, so I would say 422 - Unprocessable Entity error code is the most appropriate.
I currently have a few validation rules as follows:
\Route::post("/logError", "LogController#logError");
//In LogController
public function logError(Request $request) {
$rules = [
"name" => "required",
"message" => "required",
"level" => "in:info,debug,error"
];
$this->validate($request,$rules);
// Log the message or do whatever
});
This works fine for inputs like
[ "name"=>"Not found", "message" => "Element not found", "level" => "error" ]
[ "name"=>"Not found", "message" => "Element not found" ]`
However it throws an exception for inputs like
[ "name"=>"Not found", "message" => "Element not found", "level" => "randomgibberish" ]
My question is, since "level" is optional, is there a built-in way to validate the input and just remove optional elements that are not valid from it instead of throwing a validation exception? If not would I have to override the controller validation method to achieve this?
The validator does not modify the request input data, you need to make some sort of middleware or function in your controller that checks for the input parameters and compares them with the ones you want Laravel to check.
So yes, I think you'll need to extend the validation method, or maybe try with an helper function that does only that.
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