Input validation
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 5 of 27.
When building forms, it’s important to give users immediate feedback as they type, so they don’t submit incorrect information. This is called real-time validation.
First, let's create a basic text input field. We want to check if the username length is at least 5 characters.
<input type="text" id="username" placeholder="Enter username">Now, add an event listener to validate the input as the user types:
const usernameInput = document.getElementById('username');
const usernameError = document.getElementById('usernameError');
usernameInput.addEventListener('input', function() {
// Get the current value
const value = this.value;
// Check if it meets our criteria
if (value.length < 5) {
usernameInput.style.borderColor = "red";
} else {
usernameInput.style.borderColor = "green";
}
});The border turns red if the username is less than 5 characters and green if it’s valid.
Challenge
EasyWe have a page with an email input field. Currently, it doesn't validate the email format.
Your task is to complete the line inside the existing <strong>if</strong> block so that:
- When the email contains
"@", - The input’s border becomes
"2px solid rgb(0, 250, 0)".
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Email Validation</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<form>
<label for="email">Email:</label>
<input type="text" id="email" placeholder="Enter your email">
</form>
</div>
<script src="script.js"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.