Javascript validation for non null

Below is a code snippet where we retrieve the form value. Before further processing, check to see if it is null.

var val = document.FileList.hiddenInfo.value; alert("val is " + val); // this prints null which is as expected if (val != null) { alert("value is "+val.length); // this returns 4 } else { alert("value* is null"); } 

Any ideas why this is happening like this. ??

+75
javascript
Mar 11 '10 at 6:10
source share
9 answers

This is because val is not null , but contains 'null' as a string.

Try checking the "null" box

 if ('null' != val) 
+50
Mar 11 '10 at 6:12
source share

it will do the trick for you

 if (!!val) { alert("this is not null") } else { alert("this is null") } 
+112
Mar 11 '10 at 6:25
source share

Use !== , because != Will turn you into a world of intransitive, unknown JavaScript truth tables.

+24
Mar 11 '10 at 6:14
source share

There are three ways to check for non-null. My recommendation is to use Strict Not Version.

1. Strict not version

 if (val !== null) { ... } 

The Strict Not Version uses the "Strict Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 . !== has better performance than the != operator, because the strict equality comparison algorithm has no type values.

2. Lax is not a version

 if (val != 'null') { ... } 

The non-strict version uses the "Abstract Equality Comparison Algorithm" http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3 . != has a lower performance than the !== operator, because the abstract equality comparison algorithm compares the values.

3. Double Not Version

 if (!!val) { ... } 

Double not version !! has better performance than both the strict non-version !== and the non-strict version != ( https://jsperf.com/tfm-not-null/6 ). However, it will determine "Falsey" values, such as undefined and NaN , in False ( http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 ), which may lead to unexpected results, and it has better readability since null is not explicitly specified.

+20
Jan 15 '16 at 18:53
source share

You must use the strict comparison operator not equals !== so that if the user enters "null" , you will not end up in else .

+7
Mar 11 '10 at 6:13
source share

Perhaps because val is actually a "null" string, not a null value.

+4
Mar 11 '10 at 6:14
source share

If you want to include 0 as a valid value:

 if (!!val || val === 0) { ... } 
+2
Sep 30 '15 at 21:08
source share

This should work fine.

  if(val!= null) { alert("value is "+val.length); //-- this returns 4 } else { alert("value* is null"); } 
+1
Jul 16 '13 at 7:06 on
source share

This will work:

 if (val) { alert("Not null"); } else { alert("Null"); } 
0
Nov 20 '13 at 18:28
source share



All Articles