Menu
Coddy logo textTech

Custom error messages

Part of the JavaScript in Action section of Coddy's HTML journey — lesson 6 of 27.

Custom error messages help users understand what's wrong with their form input. Let's learn how to create and display them for form validation.

First, let's create a basic input field and a span next to it, where we will display the message:

<input type="text" id="username" placeholder="Enter username">
<span id="usernameError" class="error"></span>

Now, let's add JavaScript to validate the input and show a custom error message:

const usernameInput = document.getElementById('username');
const usernameError = document.getElementById('usernameError');

usernameInput.addEventListener('input', function() {
    if (this.value.length < 5) {
        usernameError.textContent = "Username must be at least 5 characters long";
        usernameError.style.color = "red";
    } else {
        usernameError.textContent = "";
    }
});

When a user types in the input field, the event listener checks if the username is at least 5 characters long. If not, it displays a red error message.

challenge icon

Challenge

Easy

We already have a page with an input field for the email and a message area below it.

Your task: inside the event listener, add an if–else statement that checks whether the input value includes the <strong>@</strong> symbol.

  • If it does → show the message “Looks good!”
  • Otherwise → show the message “Please enter a valid email address”

Try it yourself

<!DOCTYPE html>
<html>
<head>
  <title>Custom error messages</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="form-container">
    <h2>Create Your Account</h2>
    <p class="subtitle">Join our newsletter for the latest updates</p>

    <form>
      <label for="email">Email Address</label>
      <input type="text" id="email" placeholder="e.g. user@example.com">
      <span id="emailError" class="message"></span>

      <button type="button">Subscribe</button>
    </form>
  </div>

  <script src="script.js"></script>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in JavaScript in Action