Source Code:
(back to article)
Submit
Result:
Report an issue
<form id="registrationForm" novalidate> <label for="username">Username:</label> <input type="text" id="username" required> <button type="submit">Register</button> <span id="usernameError" style="color: red;"></span> <span id="registerSuccess" style="color: green; display: none;">Registration successful!</span> </form> <script> document.getElementById('registrationForm').addEventListener('submit', function(event) { event.preventDefault(); var input = document.getElementById('username'); var usernameError = document.getElementById('usernameError'); var registerSuccess = document.getElementById('registerSuccess'); if (!input.checkValidity()) { event.preventDefault(); // Prevent form from submitting usernameError.textContent = 'Username is required.'; registerSuccess.style.display = 'none'; // Hide success message if visible } else { usernameError.textContent = ''; // Clear error message registerSuccess.textContent = 'Registration successful!'; registerSuccess.style.display = 'block'; // Show success message input.value = ''; // Reset the username input } }); </script>