Mark As Completed Discussion

To display validation errors to the user, you can leverage the HTML5 form validation API and JavaScript. The form validation API provides several properties and methods that allow you to handle form submission and display validation messages.

When handling validation errors, you typically want to prevent the form from being submitted if there are any errors. You can achieve this by adding an event listener to the form's submit event and calling the preventDefault() method to prevent the default form submission behavior.

Here's an example of how to handle form validation errors and display an error message to the user:

JAVASCRIPT
1// Example of displaying a validation error to the user
2const form = document.getElementById('myForm');
3const emailInput = document.getElementById('email');
4const errorContainer = document.getElementById('errorContainer');
5
6form.addEventListener('submit', function(event) {
7  event.preventDefault();
8  const email = emailInput.value;
9  if (!isValidEmail(email)) {
10    errorContainer.innerText = 'Please enter a valid email';
11    return;
12  }
13
14  // Submit the form
15  form.submit();
16});
17
18function isValidEmail(email) {
19  // Email validation logic
20  const emailRegex = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)*(\.[a-zA-Z]{2,})$/;
21  return emailRegex.test(email);
22}
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment