Reputation: 3
I am implementing an HTML input field where the user has to enter his email address. I am also implementing validation on the same input field using JavaScript.
function validateEmail() {
var email = document.getElementById('EmailTextbox');
var errorMessage = document.getElementById('ErrorMessageJumbotron');
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
errorMessage.style.display = 'block';
email.style.color = '#E54A49';
email.style.border = "1px solid #E54A49";
} else {
errorMessage.style.display = 'none';
email.style.border = "1px solid #949494";
email.style.color = 'black';
}
}
* {
font-family: 'Poppins', sans-serif;
}
#EmailTextbox {
margin-bottom: 15px;
}
input[type="text"] {
font-size: 1em;
height: 45px;
width: 100%;
border: 1px solid #949494;
}
<div class="container">
<div class="jumbotron" id="ErrorMessageJumbotron" style="display: none;">
<div id="errorMessage">
<i class="fa fa-exclamation-triangle fa-2x" aria-hidden="true">
<span style="font-family: 'Poppins', sans-serif; font-weight: 500;">Please correct the marked fields.</span>
</i>
</div>
</div>
</div>
<!--container-->
<div class="container jumbotron">
<input type="text" onblur="validateEmail()" id="EmailTextbox" placeholder="E-mail address" class="form-control">
</div>
If the email is incorrect, the border of the input field is set to red and the user is prompted to enter a valid email address. However, when the user clicks on the input field, the focus is coloured blue and I want it red for this particular case. Otherwise, I want it to be blue as the default.
I have tried several approaches to try to change the focus colour using JavaScript but I did not manage to get it working properly.
Upvotes: 0
Views: 784
Reputation: 4238
Here is a simplified version of what you are trying to do, to help you achieve your end goal:
HTML
<input onblur="onEmailInputBlur(event)" placeholder="E-mail address">
CSS
input.is-invalid {
border: 1px solid red;
outline: none;
}
JS
var invalidClass = 'is-invalid';
function onEmailInputBlur(event) {
var email = event.target.value,
elClassList = event.target.classList;
elClassList.remove(invalidClass);
if (!isEmailValid(email)) {
elClassList.add(invalidClass);
}
}
function isEmailValid(email) {
var validEmailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return validEmailRegex.test(email);
}
A JsFiddle example:
https://jsfiddle.net/ybaagysn/2/
Upvotes: 2