Skip to content

Commit

Permalink
Merge pull request #3011 from BolajiOlajide/bo/allow-hex-with-prefix
Browse files Browse the repository at this point in the history
Allow 0x prefix for hex strings
  • Loading branch information
Marsup authored Jan 17, 2024
2 parents b99b177 + 32528e0 commit d2a9082
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
13 changes: 9 additions & 4 deletions lib/types/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ const internals = {
}
},
dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/,
hexRegex: /^[a-f0-9]+$/i,
hexRegex: {
withPrefix: /^(0x)?[0-9a-f]+$/i,
withoutPrefix: /^[0-9a-f]+$/i
},
ipRegex: ipRegex({ cidr: 'forbidden' }).regex,
isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,

Expand Down Expand Up @@ -364,16 +367,18 @@ module.exports = Any.extend({
hex: {
method(options = {}) {

Common.assertOptions(options, ['byteAligned']);
Common.assertOptions(options, ['byteAligned', 'withPrefix']);

options = { byteAligned: false, ...options };
options = { byteAligned: false, withPrefix: false, ...options };
assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean');
assert(typeof options.withPrefix === 'boolean', 'withPrefix must be boolean');

return this.$_addRule({ name: 'hex', args: { options } });
},
validate(value, helpers, { options }) {

if (!internals.hexRegex.test(value)) {
const re = options.withPrefix ? internals.hexRegex.withPrefix : internals.hexRegex.withoutPrefix;
if (!re.test(value)) {
return helpers.error('string.hex');
}

Expand Down
15 changes: 15 additions & 0 deletions test/types/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -4518,6 +4518,21 @@ describe('string', () => {
}]
]);
});

it('validates an hexadecimal string with prefix explicitly required', () => {

const rule = Joi.string().hex({ withPrefix: true }).strict();
Helper.validate(rule, [
['0x0123456789abcdef', true],
['123456789abcdef', true],
['0123afg', false, {
message: '"value" must only contain hexadecimal characters',
path: [],
type: 'string.hex',
context: { value: '0123afg', label: 'value' }
}]
]);
});
});

describe('hostname()', () => {
Expand Down

0 comments on commit d2a9082

Please sign in to comment.