Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic:

$request->validate([
        'firstname' => 'required',
        'lastname' => 'required',
        'username' => 'required|unique:users',
        'email' => 'required|email|unique:users',
        'password' => 'required'
    ]);

Following that, I handle errors in Axios with the following code:

.catch(error=>{
    console.log("Error: " + error.response.data.errors)
})

However, this results in displaying: Error: [object Object]

If I intentionally provide a username that already exists in the database, and then modify the catch block to

.catch(error=>{
    console.log("Error: " + error.response.data.errors.username)
})

The output will be Username is already taken which is desirable.

This poses the challenge of having to explicitly specify

error.response.data.errors.<x error>
to display the message. For instance, if I use data.errors.username but the email triggers the validation error, the console will show Error: undefined as there is no data.errors.username, only data.errors.email.

Is there a way to access and present the returned error without manual specification? Your assistance is greatly appreciated!

Answer №1

To display the error object values, you can access them by using the Object.values(errors) method to retrieve arrays of values. Then, utilize the flat() function to combine these arrays into one single array. Lastly, concatenate the values together using the join() method like so:

  console.log(Object.values(error.response.data.errors).flat().join())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to initialize a Stripe promise without using a React component?

I have encountered an issue while implementing a Stripe promise in my React app. The documentation suggests loading the promise outside of the component to prevent unnecessary recreations of the `Stripe` object: import {Elements} from '@stripe/react-s ...

Tips on displaying an array of elements as a <Dialog> within a <List>

I am currently developing a <ElementList> component that is designed to accept an array of elements through props and create a <List>, with each <ListItem> representing an element in the array. I have also included a separate component ca ...

Exploring the power of Vue element manipulation

I'm diving into the world of web development and starting my journey with Vue on an online learning platform. Check out the code snippet below: <div id="app"> <form @submit.prevent="onSubmit"> <input v-model="userName"&g ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

Leverage the response data from the first AJAX call as a variable for the second

I have a script that performs two ajax calls - the second one is nested within the success handler of the first. However, I need to utilize the data retrieved in the first success handler as an additional variable to send in the second ajax call, and then ...

Teaching Selenium how to input text into Google's login field (programming with Python)

Encountering an issue with sending keys to the username and password fields in Google's sign-in box using Selenium. Despite locating the web elements with the IDs "Email" and "Passwd", I'm unable to input any keys into them. Here is the code sni ...

Struggling to connect with PouchDB within my HTML-based Web application

I am looking to integrate pouchDB into my WebApp so that upon clicking a button, the data from a JSON file will be saved to pouchDB. In the initial stage in my index.html, I included the following: <script type="module" src="pouchdb/packa ...

Secure your text input with a masked Textfield component in Material-UI

I'm struggling to implement a mask for a TextField component, but so far I have not been successful. Although I attempted this solution, it did not work. No matter what method I try, the masking functionality just won't cooperate. Following the ...

NextJS: Retrieve the information in its initial state

Is there a way to retrieve the original format of a value? For example: The values in my textarea are: Name: Your Name Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f980968c8b9c94989095b994989095d79a9694">[email ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

The website is failing to extend and reveal content that is being concealed by jQuery

I'm currently diving into the world of Javascript and jQuery, attempting to create a functionality where upon clicking the submit button, the website dynamically expands to display search information. Although the feature is still in progress, I am ut ...

Vue3: Enhanced hook not triggered when transition is applied to component's root element

It seems like there might be something missing in the documentation, as I've observed that the updated hook is not triggered when a component's root element is wrapped in a transition. This behavior was different in Vue 2. Here are two simple exa ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

Implementing modifications to all HTML elements simultaneously

In my HTML document, there are around 80 small boxes arranged in a grid layout. Each box contains unique text but follows the same structure with three values: name, email, and mobile number. I need to switch the positions of the email and mobile number v ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

The variable within my function is not being cleared properly despite using a jQuery function

Recently, I encountered an issue with a function that displays a dialog box to ask users if their checks printed correctly. Upon clicking on another check to print, the "checked_id" value remains the same as the previously executed id. Surprisingly, this i ...

What is the best way to add child elements to existing elements?

When it comes to creating elements with jQuery, most of us are familiar with the standard method: jQuery('<div/>', { id: 'foo', href: 'http://google.com', }).appendTo('#mySelector'); However, there ar ...

Using javascript, add text to the beginning of a form before it is submitted

I'm trying to modify a form so that "https://" is added to the beginning of the input when it's submitted, without actually showing it in the text box. Here's the script I have so far: <script> function formSubmit(){ var x ...