diff --git a/zero/string.go b/zero/string.go index db1c832..1f4dc22 100644 --- a/zero/string.go +++ b/zero/string.go @@ -9,6 +9,7 @@ import ( "database/sql" "encoding/json" "fmt" + "strings" ) // nullBytes is a JSON null literal @@ -105,6 +106,11 @@ func (s String) IsZero() bool { return !s.Valid || s.String == "" } +// IsZero returns true for null empty strings or strings which consist only of blanks. +func (s String) IsZeroOrBlank() bool { + return !s.Valid || strings.ReplaceAll(s.String, " ", "") == "" +} + // Equal returns true if both strings have the same value or are both either null or empty. func (s String) Equal(other String) bool { return s.ValueOrZero() == other.ValueOrZero() diff --git a/zero/string_test.go b/zero/string_test.go index 1b691e6..633bfb0 100644 --- a/zero/string_test.go +++ b/zero/string_test.go @@ -145,6 +145,33 @@ func TestStringIsZero(t *testing.T) { } } +func TestStringIsZeroOrBlank(t *testing.T) { + str := StringFrom("test") + if str.IsZeroOrBlank() { + t.Errorf("IsZero() should be false") + } + + null := StringFrom("") + if !null.IsZeroOrBlank() { + t.Errorf("IsZeroOrBlank() should be true") + } + + empty := NewString("", true) + if !empty.IsZeroOrBlank() { + t.Errorf("IsZeroOrBlank() should be true") + } + + nullBlank := StringFrom(" ") + if !nullBlank.IsZeroOrBlank() { + t.Errorf("IsZeroOrBlank() should be true") + } + + emptyBlank := NewString(" ", true) + if !emptyBlank.IsZeroOrBlank() { + t.Errorf("IsZeroOrBlank() should be true") + } +} + func TestStringScan(t *testing.T) { var str String err := str.Scan("test")