joi icon indicating copy to clipboard operation
joi copied to clipboard

Add truthy method, like any.ok()?

Open Bartvds opened this issue 12 years ago • 5 comments

I miss a generic 'truthyness' test, like common assert.ok(). It would test for simple JavaScript boolean conversion (== and !!)

// any if truthy
schema = Joy.any().ok();

schema.validate({}, cb); // yes
schema.validate(undefined, cb); //no
schema.validate(null, cb); //no
schema.validate('0', cb); // no
schema.validate('O', cb); // yes

// or maybe make it cool and invertible
schema = Joy.any().truthy();
schema = Joy.any().falsy();

Bartvds avatar Apr 26 '14 23:04 Bartvds

You can save and reuse complex types.

var Truthy = Joi.any().invalid("",0,null,false,NaN,undefined);
var schema = Truthy;
schema.validate({}, cb) //yes
var schema2 = Truthy;
schema2.validate(false, cb) //no

cl-aaron avatar Apr 29 '14 18:04 cl-aaron

Ah, of course, that will do fine.

Consider this answered then, can be closed at your discretion.

Bartvds avatar Apr 29 '14 18:04 Bartvds

However, representing Falsy is actually trickier than I first thought.

Falsy = Joi.any().allow("",0,null,false,NaN,undefined); //doesn't work correctly
Falsy.validate(null) //returns valid
Falsy.validate(undefined) //returns valid
Falsy.validate(true) //returns valid but shouldn't
Falsy.validate({})  //returns valid but shouldn't
Falsy.validate("test") //returns valid but shouldn't

Perhaps there should be a Joi.none() which rejects all values but inherits some of any()'s interface to allow something like:

Joi.none().allow("",0,null,false,NaN,undefined);

Alternatively. if there were an inverse function to do something like Truthy.inverse() then it would easy.

cl-aaron avatar Apr 29 '14 18:04 cl-aaron

Look at the different semantics of allow() and valid().

hueniverse avatar Apr 30 '14 17:04 hueniverse

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

lock[bot] avatar Jan 09 '20 03:01 lock[bot]