Skip to content

fix: preserve 0x prefix when coercing hex string with byteAligned#3126

Open
JSap0914 wants to merge 1 commit into
hapijs:masterfrom
JSap0914:fix/hex-byteAligned-with-prefix
Open

fix: preserve 0x prefix when coercing hex string with byteAligned#3126
JSap0914 wants to merge 1 commit into
hapijs:masterfrom
JSap0914:fix/hex-byteAligned-with-prefix

Conversation

@JSap0914

Copy link
Copy Markdown

Bug

string.hex({ byteAligned: true }) combined with prefix: 'optional' or prefix: true incorrectly coerces odd-length hex strings. The coerce phase prepends '0' before the entire value — including the 0x/0X prefix — producing an invalid hex string that then fails the string.hex regex check:

Joi.string().hex({ byteAligned: true, prefix: 'optional' }).validate('0xABC');
// Before fix → { value: '00xABC', error: '"value" must only contain hexadecimal characters' }
// Expected   → { value: '0x0ABC' }

Fix

When the value starts with a 0x/0X prefix, insert the padding zero after the two-character prefix instead of before the whole string. Values without a prefix are unaffected.

Files changed: lib/types/string.js (1 line → 5 lines), test/types/string.js (18 lines added)

Verification

npx lab test/types/string.js --reporter console
# 272 tests complete (271 existing + 1 new)

AI-assisted contribution.

When string.hex({ byteAligned: true }) is used with prefix: 'optional'
or prefix: true, the coerce phase incorrectly prepended '0' before the
entire value including the '0x'/'0X' prefix (e.g. '0xABC' → '00xABC'),
producing an invalid hex string that then failed the hex regex check.

The fix inserts the padding zero after the two-character prefix so that
'0xABC' is correctly coerced to '0x0ABC' and '0XABC' to '0X0ABC'.
Values without a prefix are unaffected.
Copilot AI review requested due to automatic review settings June 18, 2026 18:13

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants