1

I have one validation that I need to perform. When a string is null or undefined or "" I need to show a message like "unable to perform further steps". If I do have values I need to proceed with further validations. I tried below code, but it doesn't work.

function test(){

  var value = undefined; // api returns undefined

  if(value != "" || value != undefined || value != null){
     alert("ID::: " + value);
     //next validations      
  }else{
    alert("Id is blank, we are unable to process the request!!!");   
    return false; 
  }

}
<button type="button"onclick="test()">Click</button>
RobIII
  • 8,488
  • 2
  • 43
  • 93
Rajasekhar
  • 2,215
  • 3
  • 23
  • 38
  • 9
    Use `&&` instead of `||` – RobIII Feb 05 '21 at 07:52
  • 2
    When the value is `undefined`, the logical OR `!= null || != undefined` returns `true` because currently it **is** `undefined` but it is **not** `null`. You need to use AND instead. – VLAZ Feb 05 '21 at 07:53
  • 3
    `null == undefined` so no need to check seperately – mousetail Feb 05 '21 at 07:54
  • 1
    also if this is input validation just doing `""` is not gonna work you have to test for more then one spaces as well – Ace Feb 05 '21 at 07:56
  • 1
    See [here](https://stackoverflow.com/questions/154059/how-can-i-check-for-an-empty-undefined-null-string-in-javascript) for more tips. – RobIII Feb 05 '21 at 08:01

3 Answers3

1

function test(){

  var value = undefined; // api returns undefined

  if(value != "" && value != undefined && value != null){
     alert("ID::: " + value);
     //next validations      
  }else{
    alert("Id is blank, we are unable to process the request!!!");   
    return false; 
  }

}
<button type="button"onclick="test()">Click</button>
张立伟
  • 11
  • 1
1

Using !someVariable converts to a boolean and handles those checks automatically

function test(){

  var value = undefined; // api returns undefined

  if(!value){
    alert("Id is blank, we are unable to process the request!!!");   
    return false; 
 }

 alert("ID::: " + value);
 //next validations  

}
<button type="button"onclick="test()">Click</button>
Jurshsmith
  • 182
  • 2
  • 4
1

Try this-

function test(){

  var value1 = undefined; // If api returns undefined
  var value2 = null; // If api returns null
  var value3 = ""; // If api returns empty string
  var value4 = 45; // If api returns any value
  
  examineValue(value1);
  examineValue(value2);
  examineValue(value3);
  examineValue(value4);
      
}

function examineValue(value) {
  if(value === "" || value === undefined || value === null){
    alert("Id is blank, we are unable to process the request!!!");   
    return false;
  }
  alert("ID::: " + value);
  //next validations  
}
<button type="button"onclick="test()">Click</button>
Neha Soni
  • 3,935
  • 2
  • 10
  • 32