I am using Laravel 5.2 for validation with a REST JSON API.
I have a UserController that extends Controller and uses the ValidatesRequests trait.
Sample code:
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id',
]);
This throws an exception, so in my Exceptions/Handler.php I have this code:
public function render($request, Exception $e)
{
return response()->json([
'responseCode' => 1,
'responseTxt' => $e->getMessage(),
], 400);
}
However, when validating responseTxt is always:
Array
(
[responseCode] => 1
[responseTxt] => The given data failed to pass validation.
)
I have used Laravel 4.2 in the past and remember the validation errors providing more detail about what failed to validate.
How can I know which field failed validation and why?
A ValidationException gets thrown which gets rendered as a single generic message if the request wants JSON.
Instead of using the validate() method, manually invoke the validator, e.g.:
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id',
]);
if ($validator->fails()) {
return new JsonResponse(['errors' => $validator->messages()], 422);
}
https://laravel.com/docs/5.2/validation#manually-creating-validators
As an aside, I'd recommend a 422 HTTP status code rather than a 400. A 400 usually implies malformed syntax. Something that causes a validation error usually means that the syntax was correct, but the data was not valid. 422 means "Unprocessable Entity"
https://www.rfc-editor.org/rfc/rfc4918#section-11.2
In Laravel 5.2 validate() method throws a Illuminate\Validation\ValidationException, so if you want to get the response use getResponse() instead getMessage().
For example, an easy way to handle this exception could be doing something like this:
try{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id'
]);
}catch( \Illuminate\Validation\ValidationException $e ){
return $e->getResponse();
}
Related
As you all may know, when we use laravel validate() function, the error status code it throws is 422. Is there a way to override or change the status code to 400?
$request->validate([ 'title' => 'required|unique:posts' ]);
With this code, when error occur, that status code it return is 422, and I want to change that to 400.
I have tried checking manually with if else, but I want to make use of the validate function because it's such a great feature.
You can use Validator for add custom code during validator fails.
For that you can try with this way:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts',
]);
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors(),
], 400);
}
I have server validation below:
$this->validate([
'first_name' => ['required','min:2','max:30',new PersonNameRule],
'last_name' => ['required','min:2','max:30',new PersonNameRule],
'username' => ['required','confirmed',new UsernameRule],
'password' => 'required|confirmed|min:6|max:20',
'birthdate' => ['required','date',new EligibleAgeRule(21)]
]);
In front-end, I intentionally fail the validation and console.log() the errors. The log returned looks like below:
Now my question is, where is the message (The given data was invalid) came from? Can I customize it?
I don't know about your objective but if your finding the file. Its in the directory
..\Illuminate\Validation\ValidationException.php.
You can edit the message you mention inside the __construct method. See example below:
public function __construct($validator, $response = null, $errorBag = 'default') {
parent::__construct('The given data was invalid.'); //change the message here
$this->response = $response;
$this->errorBag = $errorBag;
$this->validator = $validator;
}
Laravel throw an exception at $validator->fails() call.
Ok, I just want to create a stateless register method in ApiController.php with Laravel 5.7.
I used the Validator facade to check the sent data.
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
But, when I use xdebug, I see something strange. The fails methods seems throw an exception.
Laravel send an error HTML page with title:
Validation rule unique requires at least 1 parameters.
The route is used in api.php
Route::post('register', 'Api\UserController#register');
Do you have an explanation for this?
Thx for reading.
The syntax for unique rule is unique:table,column,except,idColumn.
So i changed it for you to use the users table.
If you don't want to use the users table change the users part behind unique:
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
For more information on the unique rule see this: https://laravel.com/docs/5.7/validation#rule-unique
In your API request add the following header:
...
Accept: application/json // <-----
This will tell Laravel that you want a response in a json format.
Note: this is different to the Content-type: application/json. The later indicates the format of the data tha is being sent in the body.
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 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.