Mark As Completed Discussion

Displaying Error Messages

When working with forms, it is important to provide meaningful error messages to the user when form validation fails. This helps the user understand what went wrong and how to fix it. In React, there are several ways to display error messages.

1. Simple Error Message

To display a simple error message, you can create an HTML element to hold the error message and update its content based on the validation result. Here is an example of how you can implement a simple form validation function and display an error message if the form is not valid:

JAVASCRIPT
1const nameInput = document.getElementById('name');
2const emailInput = document.getElementById('email');
3const errorMessage = document.getElementById('error-message');
4
5if (nameInput.value === '' || emailInput.value === '') {
6  errorMessage.textContent = 'Please fill in all fields';
7  return false;
8}
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment