Source Code:
(back to article)
Submit
Result:
Report an issue
<div> <form style="display: flex; justify-content: center; gap: 2px; align-items: center; flex-direction: column;" id="registrationForm" novalidate> Username: <input type="text" name="username" required> Email: <input type="email" name="email" required> <button type="submit">Register</button> </form> <div id="message" style="margin-top: 10px; text-align:center;"></div> <!-- Message container for feedback --> <script> const form = document.getElementById('registrationForm'); form.addEventListener('submit', function(event) { event.preventDefault(); // Prevent actual form submission to a server const messageDiv = document.getElementById('message'); if (!this.checkValidity()) { messageDiv.textContent = 'Please fill all required fields correctly.'; messageDiv.style.color = 'red'; // Display the message in red for errors } else { messageDiv.textContent = 'The form was successfully submitted.'; messageDiv.style.color = 'green'; // Display the message in green for success form.reset(); // Reset the form fields after successful submission } }); </script> </div>