Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Form Validation</title> </head> <body> <form id="userForm"> <input type="text" id="username" name="username" placeholder="Username" required> <input type="email" id="email" name="email" placeholder="Email" required> <button type="submit">Submit</button> </form> <script> const form = document.getElementById('userForm'); form.addEventListener('submit', (event) => { event.preventDefault(); const username = document.getElementById('username').value; const email = document.getElementById('email').value; if (!username || !email) { alert('Please fill in all fields.'); return; } if (!validateEmail(email)) { alert('Please enter a valid email address.'); return; } alert('Form submitted successfully!'); }); function validateEmail(email) { const re = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/; return re.test(email); } </script> </body> </html>