Description:
I’m encountering an issue with my JavaScript code for form validation and submission. Here’s the breakdown of what I’m trying to achieve and the problems I’m facing:
Goals:
- Allow users to add their email and submit the form.
- Display a success message with their email after successfully submitting the form.
- Implement form validation to show error messages if:
- The field is left empty.
- The email address is not formatted correctly (should end with “@gmail.com”).
Current Issues:
- The form validation is not working as expected. Even though I’m typing in an email address ending with “@gmail.com,” it only shows the error message without validating.
- When clicking on the submit button, it doesn’t take me to the page specified in another HTML file within the same project.
Code Snippets:
HTML:
<div id="main">
<div class="section">
<!-- Other HTML elements -->
<p class="Email">Email address</p>
<input type="email" id="Email" placeholder="[email protected]">
<div id="error-message"></div>
<button id="valid" type="button">Subscribe to monthly newsletter</button>
</div>
<div class="illustration-sign-up-desktop">
<img src="./assets/images/illustration-sign-up-desktop.svg" height="550px" alt="illustration-sign-up-desktop">
</div>
</div>
JavaScript:
var Email = document.getElementById('Email');
var error = document.getElementById('error-message');
var validbutton = document.getElementById('valid');
var userEmail;
Email.addEventListener('input', (e) => {
var userEmail = Email.value.toLowerCase();
var gmailRegex = /^[^@]+gmail.com$/;
if (!gmailRegex.test(userEmail)) {
error.textContent = 'Valid email required';
error.classList.add('error-message');
} else {
error.textContent = '';
error.classList.remove('error-message');
}
});
validbutton.addEventListener('click', validateEmail);
function validateEmail () {
var userEmail = Email.value.toLowerCase();
var gmailRegex = /^[^@]+gmail.com$/;
if (!gmailRegex.test(userEmail)) {
error.textContent = 'Valid email required';
error.classList.add('error-message');
} else {
// Assuming you want to navigate to 'confirmation.html' upon successful validation
window.location.href = 'confirmation.html';
}
}
Additional Notes:
- I’m using
window.location.href
to redirect to the confirmation page upon successful validation. - The email validation logic checks if the email ends with “@gmail.com”.
- Any assistance in resolving these issues would be greatly appreciated. Thank you!
New contributor
Bazooka accapella is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1