All I want to be able to do is validate an email every time the user enters a new character into the input field. When the input field is empty, it shouldn’t show anything, but when it contains letters, it should show where the invalid characters are.
My code works but doesn’t show nothing when the input field is empty because it uses the nested ‘else’ instead of the one it should use. anyone help? thanks in advance. andyy
var tick = "<img src='images/tick.png' width='20' height='20'/>";
var cross = "<img src='images/cross.png' width='20' height='20'/>";
var email_element = document.contact_form.email_field.value;
function validate_email(id) {
if ( email_element != '' ) {
var letters = /^[A-Za-z]+$/;
if ( document.contact_form.email_field.value.match(letters) )
{
document.getElementById(id).innerHTML = tick;
valid = true;
} else {
document.getElementById(id).innerHTML = cross;
valid = false;
}
} else {
document.getElementById(id).innerHTML = '';
}
return valid;
}
The problem is most likely this line:
You are assigning a global variable equal to the value of the email field, and then never updating that variable again. This does not create an “active” link to the current value of the field, it just stores the value as it was when that line was executed. Which in turn means that the first
ifstatement in your function,if ( email_element != '' ), is evaluating a non-current value of the email field.Move that line to be the first thing inside your function and then every time the function runs you’ll get the latest (current) value of that field.
EDIT: Also, you are not assigning a value to
validin the non-nested else. You should declarevalidas a local variable in the function and be sure to set it appropriately in every if and else branch (or default it to false when you declare it). As thomasruttersaid you are not currently declaring
validwith thevarstatement in your function, which means it will be created as a global variable, which in turn means that when you don’t give it a value in your non-nested else your function will return whatever valuevalidalready had from the previous call. (And really, based on the code you’ve posted, you don’t need thevalidvariable at all: you could just sayreturn true;orreturn false;directly inside each branch of your if/else structure.)