Reputation: 1533
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
Upvotes: 6
Views: 62049
Reputation: 11
**AngularJS - What is the best way to detect undefined null or empty value at the same time?**
You can define a function or you can use inline command.
$scope.isNullOrUndefined = function(value){
return (!value) && (value === null)
}
or
var temp = null;
(temp) ? 'I am not null' : 'yes I am null or undefined';
"yes I am null or undefined"
var temp = undefined
(temp) ? 'I am not null' : 'yes I am null or undefined';
"yes I am null or undefined"
temp = '123123Rec'
(temp) ? 'I am not null' : 'yes I am null or undefined';
"I am not null"
Upvotes: 1
Reputation: 61
I tried the below code, it's working perfect in my angular js application.
function isValid(value) {
return typeof value !== 'undefined';
};
Upvotes: 0
Reputation: 14205
As mentioned in the comments it's better to use return !value
.
$scope.isValid = function(value) {
return !value
}
A proper way is simply to use angular.isDefined()
Upvotes: 6
Reputation: 9597
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.
Upvotes: 14