Skip to content

Commit b532225

Browse files
BolajiOlajideMarsup
authored andcommitted
add tests
1 parent 821b268 commit b532225

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

lib/types/string.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ const internals = {
2727
}
2828
},
2929
dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/,
30-
hexRegex: /^(0x)?[0-9a-f]+$/i,
30+
hexRegex: {
31+
withPrefix: /^(0x)?[0-9a-f]+$/i,
32+
withoutPrefix: /^[0-9a-f]+$/i
33+
},
3134
ipRegex: Ip.regex({ cidr: 'forbidden' }).regex,
3235
isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,
3336

@@ -368,16 +371,18 @@ module.exports = Any.extend({
368371
hex: {
369372
method(options = {}) {
370373

371-
Common.assertOptions(options, ['byteAligned']);
374+
Common.assertOptions(options, ['byteAligned', 'withPrefix']);
372375

373-
options = { byteAligned: false, ...options };
376+
options = { byteAligned: false, withPrefix: false, ...options };
374377
Assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean');
378+
Assert(typeof options.withPrefix === 'boolean', 'withPrefix must be boolean');
375379

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

380-
if (!internals.hexRegex.test(value)) {
384+
const re = options.withPrefix ? internals.hexRegex.withPrefix : internals.hexRegex.withoutPrefix;
385+
if (!re.test(value)) {
381386
return helpers.error('string.hex');
382387
}
383388

test/types/string.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4487,6 +4487,21 @@ describe('string', () => {
44874487
}]
44884488
]);
44894489
});
4490+
4491+
it('validates an hexadecimal string with prefix explicitly required', () => {
4492+
4493+
const rule = Joi.string().hex({ withPrefix: true }).strict();
4494+
Helper.validate(rule, [
4495+
['0x0123456789abcdef', true],
4496+
['123456789abcdef', true],
4497+
['0123afg', false, {
4498+
message: '"value" must only contain hexadecimal characters',
4499+
path: [],
4500+
type: 'string.hex',
4501+
context: { value: '0123afg', label: 'value' }
4502+
}]
4503+
]);
4504+
});
44904505
});
44914506

44924507
describe('hostname()', () => {

0 commit comments

Comments
 (0)