Skip to content

Commit 32528e0

Browse files
committed
add tests
1 parent 504e8f0 commit 32528e0

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
@@ -23,7 +23,10 @@ const internals = {
2323
}
2424
},
2525
dataUriRegex: /^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/,
26-
hexRegex: /^(0x)?[0-9a-f]+$/i,
26+
hexRegex: {
27+
withPrefix: /^(0x)?[0-9a-f]+$/i,
28+
withoutPrefix: /^[0-9a-f]+$/i
29+
},
2730
ipRegex: ipRegex({ cidr: 'forbidden' }).regex,
2831
isoDurationRegex: /^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,
2932

@@ -364,16 +367,18 @@ module.exports = Any.extend({
364367
hex: {
365368
method(options = {}) {
366369

367-
Common.assertOptions(options, ['byteAligned']);
370+
Common.assertOptions(options, ['byteAligned', 'withPrefix']);
368371

369-
options = { byteAligned: false, ...options };
372+
options = { byteAligned: false, withPrefix: false, ...options };
370373
assert(typeof options.byteAligned === 'boolean', 'byteAligned must be boolean');
374+
assert(typeof options.withPrefix === 'boolean', 'withPrefix must be boolean');
371375

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

376-
if (!internals.hexRegex.test(value)) {
380+
const re = options.withPrefix ? internals.hexRegex.withPrefix : internals.hexRegex.withoutPrefix;
381+
if (!re.test(value)) {
377382
return helpers.error('string.hex');
378383
}
379384

test/types/string.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4518,6 +4518,21 @@ describe('string', () => {
45184518
}]
45194519
]);
45204520
});
4521+
4522+
it('validates an hexadecimal string with prefix explicitly required', () => {
4523+
4524+
const rule = Joi.string().hex({ withPrefix: true }).strict();
4525+
Helper.validate(rule, [
4526+
['0x0123456789abcdef', true],
4527+
['123456789abcdef', true],
4528+
['0123afg', false, {
4529+
message: '"value" must only contain hexadecimal characters',
4530+
path: [],
4531+
type: 'string.hex',
4532+
context: { value: '0123afg', label: 'value' }
4533+
}]
4534+
]);
4535+
});
45214536
});
45224537

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

0 commit comments

Comments
 (0)