Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

laravel display validation errors ajax

// php
public function store(Request $request)
{
  	$validator = Validator::make( $request->all(),[
            'first_name' => 'string',
            'last_name' => 'string',
            'phone_number' => ['string', 'max:14'],
            'email' => 'email'
      ]);
        
      if($validator->fails())
        {
            $response = "<div class='alert alert-danger'><ul>";
            foreach($validator->errors()->all() as $error)
            {
              $response .= "<li> {$error}</li>";  
            }
            $response .= "</ul></div>";
            return response()->json([
                'message' => $response
            ], 201);
        }
  
  // no errors
  //continue with your logic
}

// javascript (jQuery)
$.ajax({
  url: 'your_backend_url',
  type: 'POST/PUT',
  data: request_data, // maybe $(this).serializeArray()
  beforeSend: () => {
    // any stuff that you would like to do before sending the request,maybe showing a loader
  },
  success: (response, responseText, xhr) => {
     if(xhr.status === 201)
      {
        // put errors in some element above or below the form
        return $(".errors").html(response.message)
      }
    // clear previous errors
    $(".errors").html("");
    // success stuff here
    }
});
 
PREVIOUS NEXT
Tagged: #laravel #display #validation #errors #ajax
ADD COMMENT
Topic
Name
6+4 =