Skip to content

Commit

Permalink
Improve isValid for strings
Browse files Browse the repository at this point in the history
  • Loading branch information
SeanReece authored and durran committed Sep 5, 2024
1 parent 5a8900e commit bc20e7a
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/objectid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export class ObjectId extends BSONValue {
// If intstanceof matches we can escape calling ensure buffer in Node.js environments
this.buffer = ByteUtils.toLocalBufferType(workingId);
} else if (typeof workingId === 'string') {
if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
if (ObjectId.validateHexString(workingId)) {
this.buffer = ByteUtils.fromHex(workingId);
} else {
throw new BSONError(
Expand Down Expand Up @@ -143,6 +143,15 @@ export class ObjectId extends BSONValue {
}
}

/**
* @internal
* Validates the input string is a valid hex representation of an ObjectId.
*/
private static validateHexString(input: string): boolean {
if (input == null || input.length !== 24) return false;
return checkForHexRegExp.test(input);
}

/** Returns the ObjectId id as a 24 lowercase character hex string representation */
toHexString(): string {
if (ObjectId.cacheHexString && this.__id) {
Expand Down Expand Up @@ -329,6 +338,7 @@ export class ObjectId extends BSONValue {
*/
static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean {
if (id == null) return false;
if (typeof id === 'string') return ObjectId.validateHexString(id);

try {
new ObjectId(id);
Expand Down

0 comments on commit bc20e7a

Please sign in to comment.