Ваше условие if в валидации недопустимо:
email.value && password.value === '' || email.value && password.value == null
Вы не можете проверить, являются ли два значения пустыми одновременно, и так как поле является текстовым полем, они никогда не могут быть нулевыми. Вы можете сделать:
email.value === '' || password.value === ''
Или объединить несколько if, чтобы иметь отдельные сообщения:
const email = document.getElementById('email')
const password = document.getElementById('password')
const form = document.getElementById('login')
// Be carefule, getElementsByClassName returns an array, not a single element
const errorElement = document.getElementsByClassName('alert')[0]
// If you always want a single element you can use
// const errorElement = document.querySelector('.alert')
form.addEventListener('submit', function(e) {
let messages = []
errorElement.innerText = '';
errorElement.parentElement.style.display = 'none';
if (email.value === '') {
messages.push('Empty email');
}
if (password.value === '') {
messages.push('Empty password');
}
if (messages.length > 0) {
e.preventDefault()
errorElement.innerText = messages.join(', ');
errorElement.parentElement.style.display = 'block';
}
})
<div class="login">
<h1>Login</h1>
<div style="display:none;">
<span class="alert"></span>
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
</div>
<form id="login" name="login" action="" method="post">
<input type="text" name="email" placeholder="Email Address" id="email">
<input type="password" name="password" placeholder="Password" id="password">
<input type="submit" value="Login" name="login">
<input type="button" value="Register" onclick="location.href= 'register.php'">
</form>
</div>
Обновление Я добавил базовый пример того, как скрыть / показать ошибки.