Only one if/else statement executing
Clarisse’s Question:
I have two if/else statements comparing the same variable, with in one function. I do not desire, nor see a reason to nest the statements.
function checkUser() {
var user = document.getElementById('usern').value;
var element = document.getElementById('labelUser');
if (user.length < 3 || user.length > 15) {
element.innerHTML = "Invalid length.";
element.style.color = "red";
}
else {
element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';
}
if (user.match(/[<>!@#$%^&*,]+/i)){
element.innerHTML = "Invalid characters.";
element.style.color = "red";
}
else {
element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';
}
}
How could this code be improved?
function checkUser() {
var user = document.getElementById('usern').value;
var element = document.getElementById('labelUser');
if (user.length < 3 || user.length > 15) {
element.innerHTML = "Invalid length.";
element.style.color = "red";
}
else if (user.match(/[<>!@#$%^&*,]+/i)){
element.innerHTML = "Invalid characters.";
element.style.color = "red";
}
else {
element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';
}
}
You can minimize the code like this:
var gotoElse = false;
if (user.length < 3 || user.length > 15) {
element.innerHTML = "Invalid length.";
element.style.color = "red";
}
else gotoElse = true;
if (user.match(/[<>!@#$%^&*,]+/i)){
element.innerHTML = "Invalid characters.";
element.style.color = "red";
}
else gotoElse = true;
if(gotoElse) {
element.innerHTML = '<img src="http://www.zrfunding.com/wp-content/uploads/2013/05/CheckMarkSmallGreen.jpg" alt="Valid" height="35" width="30"/>';
}