Skip to content

Commit

Permalink
Fix: Joi string => null is different than undefined (#295)
Browse files Browse the repository at this point in the history
  • Loading branch information
klesgidis authored May 31, 2022
1 parent b9f081f commit 71b75e8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/initializers/joi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const Joi: JoiWithExtensions = _Joi.extend(
type: 'string',
base: joi.string(),
prepare: (val, helpers) => {
let newVal = val === null || val === undefined ? undefined : clearNullByte(val);
let newVal = val === null || val === undefined ? val : clearNullByte(val);

const defaultIfEmptyRule = helpers.schema.$_getRule('defaultIfEmpty');
if (defaultIfEmptyRule?.args?.v) {
Expand Down
14 changes: 11 additions & 3 deletions test/initializers/joi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,17 @@ describe('joi extensions', function () {
Joi.stringWithEmpty().validate(`asd ${String.fromCharCode(0, 0)}asd`).value.should.equal('asd asd');
});
it('allows empty or null values', function () {
should(Joi.stringWithEmpty().validate('').error).be.undefined();
should(Joi.stringWithEmpty().validate(null).error).be.undefined();
should(Joi.stringWithEmpty().validate(undefined).error).be.undefined();
const result1 = Joi.stringWithEmpty().validate('');
should(result1.error).be.undefined();
result1.value.should.equal('');

const result2 = Joi.stringWithEmpty().validate(null);
should(result2.error).be.undefined();
should(result2.value).be.null();

const result3 = Joi.stringWithEmpty().validate(undefined);
should(result3.error).be.undefined();
should(result3.value).be.undefined();
});
describe('defaultIfEmpty', function () {
it('with empty string', function () {
Expand Down

0 comments on commit 71b75e8

Please sign in to comment.