I wanted to check the entered email address properly with a Javascript function like this:
function validation() {
let form = document.getElementById('form')
let email = document.getElementById('email').value
let text = document.getElementById('text')
let pattern = "/^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/"
if (email.match(pattern)) {
form.classList.add('valid')
form.classList.remove('invalid')
text.innerHTML = "Valid"
text.style.color = '#00ff00'
} else {
form.classList.remove('valid')
form.classList.add('invalid')
text.innerHTML = "Not valid"
text.style.color = '#ff0000'
}
if (email == '') {
form.classList.remove('valid')
form.classList.remove('invalid')
text.innerHTML = ""
text.style.color = '#00ff00'
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<input type="email" name="email" class="form-control" id="email" placeholder="Enter your email" onkeydown="validation()">
<span id="text"></span>
</div>
</form>
Now it calls the validation()
function properly and shows Not Valid message if user has entered an email address which is not validated.
But the problem comes from when the user tries to correct his email address and enters a valid email, but the message Not Valid still appears on page because of last incorrect email address.
So how can I properly hide this message when user enters valid email the 2nd time?