Skip to content Skip to sidebar Skip to footer

Reactjs - How To Log The Specific Field That Is Causing A 400 Error Code When Submitting Form

I am currently working on a web app that uses ReactJS as the frontend, and DRF as the backend, and I am working on the form validation right now. In the backend, for fields that ar

Solution 1:

Okay, took some time and googling but figured it out, I can find the specifics of the error under error.response data.

This is what I did to my axios call (btw I am using DRF so im not sure if it would work for other backend systems)

.catch(error => {
       console.log(error.response.data)
  )}

Which would log out the errors flagged out by the backend when trying to post the request. It comes in the form of an object, with the keys of the object as the field name, and the value of the corresponding key would be an array of the errors flagged out.

For example, the error message I got was:

{telephone_number: ["The phone number entered is not valid."]}

From there, I was able to render the relevant error messages onto the relevant fields by matching the key of the object to the name of the field.

Hope this has helped some people, it certainly helped me!

Post a Comment for "Reactjs - How To Log The Specific Field That Is Causing A 400 Error Code When Submitting Form"