diff --git a/bson/primitive/objectid.go b/bson/primitive/objectid.go index a0eb5378cb..ae82023296 100644 --- a/bson/primitive/objectid.go +++ b/bson/primitive/objectid.go @@ -88,6 +88,16 @@ func ObjectIDFromHex(s string) (ObjectID, error) { return oid, nil } +// IsValidObjectID judges given string format is valid or invalid for ObjectID. +func IsValidObjectID(s string) bool { + _, err := ObjectIDFromHex(s) + if err != nil { + return false + } + + return true +} + // MarshalJSON returns the ObjectID as a string func (id ObjectID) MarshalJSON() ([]byte, error) { return json.Marshal(id.Hex()) diff --git a/bson/primitive/objectid_test.go b/bson/primitive/objectid_test.go index e8336afbea..78f0a12516 100644 --- a/bson/primitive/objectid_test.go +++ b/bson/primitive/objectid_test.go @@ -46,6 +46,27 @@ func TestFromHex_WrongLength(t *testing.T) { require.Equal(t, ErrInvalidHex, err) } +func TestIsValidObjectID(t *testing.T) { + testCases := []struct { + givenID string + expected bool + }{ + { + givenID: "5ef7fdd91c19e3222b41b839", + expected: true, + }, + { + givenID: "5ef7fdd91c19e3222b41b83", + expected: false, + }, + } + + for _, testcase := range testCases { + got := IsValidObjectID(testcase.givenID) + require.Equal(t, testcase.expected, got) + } +} + func TestTimeStamp(t *testing.T) { testCases := []struct { Hex string