joi icon indicating copy to clipboard operation
joi copied to clipboard

Combine uppercase with valid

Open pon opened this issue 11 years ago • 13 comments

Is it possible to use string.uppercase() prior to running through the any.valid() method?

pon avatar Feb 25 '15 23:02 pon

What difference would it make ?

Marsup avatar Feb 26 '15 00:02 Marsup

I would like Joi.string().valid('AA','BB') to be able to accept the following values: ['aa','aA', Aa', ...] without having to expand the array to cover all string cases.

pon avatar Feb 26 '15 00:02 pon

So you want Joi.string().insensitive() which already exists then.

Marsup avatar Feb 26 '15 08:02 Marsup

So that works for the validation piece, but I lose the functionality of the resulting value being uppercase after validation takes place. Any way to have both?

pon avatar Feb 26 '15 17:02 pon

@hueniverse do you mind helping me understand that https://github.com/hapijs/joi/commit/0b4b45aa6548e2444d9bb976e07653f2af1e4e97 ? Is it purely optimization ?

Marsup avatar Feb 26 '15 23:02 Marsup

@pon until I find a solution, a hack that works is :

Joi.string().insensitive().uppercase().concat(Joi.string().valid(['AA', 'BB', ...]))

Marsup avatar Feb 27 '15 00:02 Marsup

@Marsup - running the code below still returns the non-uppercased value:

var Joi = require('joi');

var schema = {
  key: Joi.string().insensitive().uppercase().concat(Joi.string().valid(['AA', 'BB']))
};

Joi.validate({ key: 'aa' }, schema, function (err, value) {
  // value = { key: 'aa' }
});

pon avatar Mar 01 '15 19:03 pon

My bad, thought it was working for a moment.

Marsup avatar Mar 01 '15 19:03 Marsup

No problem - I have a non-Joi workaround for now

pon avatar Mar 01 '15 19:03 pon

Best I can think of is this :

var schema = {
  key: Joi.string().uppercase().regex(/^AA|BB$/)
};

Marsup avatar Mar 01 '15 19:03 Marsup

I came across this as well, and would like to see a solution. Especially for my "lout" documentation I would prefer the combination with valid over regex.

KeKs0r avatar Apr 26 '15 21:04 KeKs0r

I'm still thinking about how to lessen the performance impact of such modification.

Marsup avatar Apr 27 '15 07:04 Marsup

I was also expecting Joi.string().uppercase().valid('A', 'B') to solve this use case.

As far as 0b4b45a is concerned, after reading the documentation I get the impression that using .min(2).valid(2, 3, 4) is really the problem as they contradict each other. So to truly solve this I guess joi would have to distinguish between modification rules (trim(), lowercase() etc) and validation rules. And then the assertion "Cannot define rules when valid values specified" would only be applied to the latter.

rudolf avatar Feb 10 '16 08:02 rudolf