Skip to content

Commit b88bb74

Browse files
kachickDivjot Arora
authored andcommitted
GODRIVER-1893 Add primitive.IsValidObjectID function (#592)
1 parent ccdaffc commit b88bb74

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

bson/primitive/objectid.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,16 @@ func ObjectIDFromHex(s string) (ObjectID, error) {
8888
return oid, nil
8989
}
9090

91+
// IsValidObjectID judges given string format is valid or invalid for ObjectID.
92+
func IsValidObjectID(s string) bool {
93+
_, err := ObjectIDFromHex(s)
94+
if err != nil {
95+
return false
96+
}
97+
98+
return true
99+
}
100+
91101
// MarshalJSON returns the ObjectID as a string
92102
func (id ObjectID) MarshalJSON() ([]byte, error) {
93103
return json.Marshal(id.Hex())

bson/primitive/objectid_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,27 @@ func TestFromHex_WrongLength(t *testing.T) {
4646
require.Equal(t, ErrInvalidHex, err)
4747
}
4848

49+
func TestIsValidObjectID(t *testing.T) {
50+
testCases := []struct {
51+
givenID string
52+
expected bool
53+
}{
54+
{
55+
givenID: "5ef7fdd91c19e3222b41b839",
56+
expected: true,
57+
},
58+
{
59+
givenID: "5ef7fdd91c19e3222b41b83",
60+
expected: false,
61+
},
62+
}
63+
64+
for _, testcase := range testCases {
65+
got := IsValidObjectID(testcase.givenID)
66+
require.Equal(t, testcase.expected, got)
67+
}
68+
}
69+
4970
func TestTimeStamp(t *testing.T) {
5071
testCases := []struct {
5172
Hex string

0 commit comments

Comments
 (0)