#Form Error Handling

6 messages · Page 1 of 1 (latest)

small magnet
#

Hey guys,
I am building a little app as a project. That app concludes a form and I want to get rid of that little pop up window, whenever there is a problem with the content in that input field. Instead of that I want the message to be shown up under that input field.

Do you guys know how I can handle stuff like that with React?

proud wadi
#

You can do your own implementation or use a schema validator to validate your inputs.
If you go with the schema validator, I highly recommend zod: https://zod.dev/

otherwise you can have a state that is an empty object by default, then whenever your value changes or you submit the form you run your validation on your inputs and populate the error state.

#

If you'd like I can provide a basic implementation but it would be better if you experiment with it

wispy ether
#

@small magnet My go-to approach for this is to have 2 extra pieces of state - error and emptyFields. The error state displays any error messages from the validation, and the emptyFields state keeps track of any empty required fields.

https://scrimba.com/scrim/c4WE3gcp

Here's a quick and dirty example of this in action. When the user clicks the "submit form" button, the formSubmit function checks to see if the name and email fields are empty. If they are, they pass a string into the emptyFields state, which in turn gives the relevant inputs an "invalid" class, turning their borders red. This also sets the error message and displays it on the screen.

You can add as many different types of validation checks as you like to this, including things like checking for a valid email address, comparing fields, etc and display any error messages you like to the user.

#

The beauty about this approach is that you can use the same error state to display any errors that come back from a try-catch to a server or api.

small magnet
#

Jesus Christ, my App works. Because of your guys help I could remove like 50 lines of code and made my solution way more readable. Thank you guys so much! Big help!