Skip to content

fix(isMongoId): reject 0x-prefixed strings#2777

Open
chatman-media wants to merge 1 commit into
validatorjs:masterfrom
chatman-media:fix/ismongoid-0x-prefix
Open

fix(isMongoId): reject 0x-prefixed strings#2777
chatman-media wants to merge 1 commit into
validatorjs:masterfrom
chatman-media:fix/ismongoid-0x-prefix

Conversation

@chatman-media

Copy link
Copy Markdown

Problem

isMongoId() incorrectly returns true for 0x-prefixed (and 0X/0h) 24-character strings:

isMongoId('0xaaaaaaaaaaaaaaaaaaaaaa'); // => true  (should be false)

A MongoDB ObjectId is exactly 24 hexadecimal characters with no prefix.

Root cause

isMongoId delegates to isHexadecimal, whose regex is prefix-tolerant:

const hexadecimal = /^(0x|0h)?[0-9A-F]+$/i;

It accepts an optional leading 0x/0h. isMongoId then only checked str.length === 24, so 0x + 22 hex digits = 24 characters slips through both checks.

Fix

Validate strictly with a direct regex instead of delegating to the prefix-tolerant isHexadecimal:

const mongoId = /^[0-9a-f]{24}$/i;

This requires exactly 24 hex characters and rejects any 0x/0X/0h prefix. Valid ObjectIds (e.g. 507f1f77bcf86cd799439011) still pass.

Tests

Added 0xaaaaaaaaaaaaaaaaaaaaaa and 0Xaaaaaaaaaaaaaaaaaaaaaa to the isMongoId invalid cases. The test fails on master and passes with this fix. Full suite green, lint clean, coverage unchanged.

@codecov

codecov Bot commented Jun 18, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3d2f4b3) to head (f266f8a).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #2777   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          114       114           
  Lines         2587      2587           
  Branches       656       655    -1     
=========================================
  Hits          2587      2587           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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.

1 participant