Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Javascript: Is there anything I can do to improve this valid-state function?

I have this function in an AngularJS service:

self.IsValid = function (entity) {
    if (entity == undefined || entity == "undefined")
        return false;

    if (entity == null)
        return false;

    if (entity == "00000000-0000-0000-0000-000000000000")
        return false;

    return true;
}

A working sample here.

Is there anything I can do to improve on this? Or maybe there's a better way altogether?

PS: Resharper says that the entity == null check is always false, but that doesn't feel right, I could have passed null.

like image 276
Spikee Avatar asked Feb 04 '26 00:02

Spikee


1 Answers

You can use

self.IsValid = function(entity) {
    return (entity !== "undefined" && entity !== "00000000-0000-0000-0000-000000000000") && !!entity;
};
  1. entity !== "undefined" && entity !== "00000000-0000-0000-0000-000000000000": Checks if the value of entity variable is not 'undefined' and '00000000-0000-0000-0000-000000000000'. If the expression evaluates to false the result will be returned.
  2. !! will cast the value to Boolean. See What is the !! (not not) operator in JavaScript?

Updated Plunker

like image 72
Tushar Avatar answered Feb 06 '26 14:02

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!