Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript validation of multiple Booleans [duplicate]

Tags:

javascript

I want to validate an object that has three Boolean properties, of which one, and only one, must be true. What is the best way to check this?

I came up with this:

var t1 = obj.isFirst  ? 1 : 0,
    t2 = obj.isSecond ? 1 : 0,
    t3 = obj.isThird  ? 1 : 0;

var valid = (t1 + t2 + t3) === 1;

This works fine, but it feels a bit like a hobbyists solution :-)

Is there a better way of doing this? Using XOR (^) for example?

like image 631
Michiel Avatar asked Jul 17 '18 14:07

Michiel


Video Answer


3 Answers

You could filter the Object.values and check if the length is 1

let obj = {
    a: true,
    b: false,
    c: false
};
let oneTrue = Object.values(obj).filter(e => e === true).length === 1;
console.log(oneTrue);

As @deceze commented

Should there be more properties in the object: [obj.a, obj.b, obj.c].filter(Boolean)...


Note that in your case, it might make sense to add a method to your object that does the check for you

let obj = {
    a: false,
    b: false,
    c: false,
    isValid() {
        return this.a + this.b + this.c === 1;
    }
};

console.log(obj.isValid());
like image 112
baao Avatar answered Oct 19 '22 08:10

baao


You can use array.reduce:

var obj = {
    a: true,
    b: false,
    c: false
};
var res = Object.values(obj).reduce((m, o) => m + o) === 1;
console.log(res);
like image 25
Faly Avatar answered Oct 19 '22 08:10

Faly


Use:

obj.isFirst + obj.isSecond + obj.isThird === 1

Assuming it is certain that the values are Booleans and not something different. You can add explicit conversion if you like, like this:

Number(obj.isFirst) + Number(obj.isSecond) + Number(obj.isThird) === 1

But JavaScript also implicitly does this conversion for you.

(This is based on ASDFGerte’s comment.)

like image 7
2 revs, 2 users 71% Avatar answered Oct 19 '22 08:10

2 revs, 2 users 71%