From b88bb74e33a8c6d1b0fa61afbe0cd98544778853 Mon Sep 17 00:00:00 2001 From: Kenichi Kamiya Date: Wed, 3 Mar 2021 08:24:22 +0900 Subject: [PATCH] GODRIVER-1893 Add primitive.IsValidObjectID function (#592) --- bson/primitive/objectid.go | 10 ++++++++++ bson/primitive/objectid_test.go | 21 +++++++++++++++++++++ 2 files changed, 31 insertions(+) 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