描述:
我的表单验证和提交 JavaScript 代码遇到问题。以下是我想要实现的目标和面临的问题的细分:
目标:
当前问题:
代码片段:
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';
}
}
补充说明:
window.location.href
在成功验证后重定向到确认页面。您可以使用内置的表单验证。如果有任何必填的表单字段,则在提交表单之前它们都必须有效。
电子邮件的有效性基于输入元素上的模式属性。
document.forms.form01.addEventListener('invalid', e => {
e.preventDefault();
e.target.classList.add('invalid');
}, true);
document.forms.form01.addEventListener('input', e => {
if(e.target.validity.valid){
e.target.classList.remove('invalid');
}
});
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
window.location.href = 'confirmation.html';
});
.error-message {
visibility: hidden;
}
input.invalid~.error-message {
visibility: visible;
}
<div id="main">
<div class="section">
<!-- Other HTML elements -->
<form name="form01">
<p class="Email">Email address</p>
<input type="email" name="Email" placeholder="[email protected]"
pattern=".*@[gG][mM][aA][iI][lL]\.[cC][oO][mM]" required>
<div class="error-message">Valid email required</div>
<button type="submit">Subscribe to monthly newsletter</button>
</form>
</div>
</div>