@@ -4,9 +4,6 @@ import { type InspectFn, defaultInspect } from './parser/utils';
4
4
import { ByteUtils } from './utils/byte_utils' ;
5
5
import { NumberUtils } from './utils/number_utils' ;
6
6
7
- // Regular expression that checks for hex value
8
- const checkForHexRegExp = new RegExp ( '^[0-9a-fA-F]{24}$' ) ;
9
-
10
7
// Unique sequence for the current process (initialized on first use)
11
8
let PROCESS_UNIQUE : Uint8Array | null = null ;
12
9
@@ -112,7 +109,7 @@ export class ObjectId extends BSONValue {
112
109
// If intstanceof matches we can escape calling ensure buffer in Node.js environments
113
110
this . buffer = ByteUtils . toLocalBufferType ( workingId ) ;
114
111
} else if ( typeof workingId === 'string' ) {
115
- if ( workingId . length === 24 && checkForHexRegExp . test ( workingId ) ) {
112
+ if ( ObjectId . validateHexString ( workingId ) ) {
116
113
this . buffer = ByteUtils . fromHex ( workingId ) ;
117
114
} else {
118
115
throw new BSONError (
@@ -143,6 +140,29 @@ export class ObjectId extends BSONValue {
143
140
}
144
141
}
145
142
143
+ /**
144
+ * @internal
145
+ * Validates the input string is a valid hex representation of an ObjectId.
146
+ */
147
+ private static validateHexString ( string : string ) : boolean {
148
+ if ( string ?. length !== 24 ) return false ;
149
+ for ( let i = 0 ; i < 24 ; i ++ ) {
150
+ const char = string . charCodeAt ( i ) ;
151
+ if (
152
+ // Check for ASCII 0-9
153
+ ( char >= 48 && char <= 57 ) ||
154
+ // Check for ASCII a-f
155
+ ( char >= 97 && char <= 102 ) ||
156
+ // Check for ASCII A-F
157
+ ( char >= 65 && char <= 70 )
158
+ ) {
159
+ continue ;
160
+ }
161
+ return false ;
162
+ }
163
+ return true ;
164
+ }
165
+
146
166
/** Returns the ObjectId id as a 24 lowercase character hex string representation */
147
167
toHexString ( ) : string {
148
168
if ( ObjectId . cacheHexString && this . __id ) {
@@ -329,6 +349,7 @@ export class ObjectId extends BSONValue {
329
349
*/
330
350
static isValid ( id : string | number | ObjectId | ObjectIdLike | Uint8Array ) : boolean {
331
351
if ( id == null ) return false ;
352
+ if ( typeof id === 'string' ) return ObjectId . validateHexString ( id ) ;
332
353
333
354
try {
334
355
new ObjectId ( id ) ;
0 commit comments