September 9, 2013

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"/>';  
  }     

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!