Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - What is the best way to detect undefined null or empty value at the same time?

Tags:

angularjs

Sometimes I need to check a value for three conditions at the same time, null, undefined or "". Due that I haven´t found any method to do this, I coded my own and it works.

$scope.isNullOrEmptyOrUndefined = function (value) {
    if (value === "" || value === null || typeof value === "undefined") {
        return true;
    }
}

Just wanted to know if there is a better way to accomplish the same thing.

Thanks so much in advance,

Guillermo

like image 779
Guillermo Avatar asked Oct 15 '14 18:10

Guillermo


People also ask

How check variable is empty or not in AngularJS?

isUndefined() function in AngularJS is used to determine the value inside isUndefined function is undefined or not. It returns true if the reference is undefined otherwise returns false. Return Value: It returns true if the value passed is undefined else returns false.

How do you handle undefined and null in Javascript?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .

Is null or empty angular?

How to check if a variable string is empty or undefine or null in Angular. In template HTML component: We can use the ngIf directive to check empty null or undefined. In this example, if stringValue is empty or null, or undefined, It prints the empty message.


2 Answers

How about this? Since you seem to be returning true in those null/undefined cases:

$scope.isNullOrEmptyOrUndefined = function (value) {
    return !value;
}

http://jsfiddle.net/1feLd9yn/3/

Note that an empty array and empty object will also return false as they are truthy values. If you want the true/false return to be flip-flopped, then omit the ! before value.

like image 82
sma Avatar answered Oct 06 '22 19:10

sma


Update

As mentioned in the comments it's better to use return !value.

$scope.isValid = function(value) {
    return !value
}

Old and incomplete Answer

A proper way is simply to use angular.isDefined()

like image 42
gearsdigital Avatar answered Oct 06 '22 19:10

gearsdigital