Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation errors in AJAX mode

Currently I use this to display validation errors via ajax:

            if (data.validation_failed == 1)             {                 var arr = data.errors;                 $.each(arr, function(index, value)                 {                     if (value.length != 0)                     {                         $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');                     }                 });                 $('#ajax-loading').hide();                 $("#validation-errors").show();             } 

It works fine, does exactly what I need.

The problem is what I have to do to transport the errors from laravel to ajax:

    $rules = array(          'name'  => 'required',         'password' => 'required'     );      $v = Validator::make(Input::all(), $rules);      if ( ! $v->passes())     {      $messages = $v->messages();      foreach ($rules as $key => $value)     {         $verrors[$key] = $messages->first($key);     }          if(Request::ajax())         {                                 $response_values = array(                 'validation_failed' => 1,                 'errors' => $verrors);                       return Response::json($response_values);         }         else         {         return Redirect::to('login')             ->with('validation_failed', 1)             ->withErrors($v);         }             } 

If I want to have the field names as key, I have to iterate $rules, but even if I don't use field names as key, yet I have to iterate error messages to construct $verrors.

How could I convert $v->messages() to the equivalent of $verrors without the need to iterate? Since Response::json() is expecting an array instead of an object.

like image 921
user2094178 Avatar asked Jun 13 '13 21:06

user2094178


People also ask

What is validation in Ajax?

With Ajax, the data added to the form can be dynamically validated as the data is added to form fields using business logic in a server application. Thus, a complete form does not have to be posted to the server to check if data in the form is valid.

How to display error Message using ajax?

If it is a valid number then an alert message is displayed inside the jQuery AJAX Success event handler and if an exception occurs in the WebMethod, the thrown exception is caught inside the jQuery AJAX Error event handler and which makes a call to the OnError JavaScript function which processes and displays the ...


2 Answers

The easiest way is to leverage the MessageBag object of the validator. This can be done like this:

// Setup the validator $rules = array('username' => '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": {         "username": [             "The username field is required."         ],         "password": [             "The password field is required."         ]     } } 
like image 159
DerLola Avatar answered Oct 01 '22 02:10

DerLola


In the ajax response trying something like

    .fail(function( data ) {         var response = JSON.parse(data.responseText);         var errorString = '<ul>';         $.each( response.errors, function( key, value) {             errorString += '<li>' + value + '</li>';         });         errorString += '</ul>'; 
like image 20
Sports Racer Avatar answered Oct 01 '22 01:10

Sports Racer