From a8a2dffc5918b6439e36d9117c96efb4e1d041ca Mon Sep 17 00:00:00 2001 From: chesedo Date: Fri, 6 Jan 2017 10:11:08 +0200 Subject: [PATCH] Have Required validator trim strings to fix #2361 This will cause the Required validator not to consider fields that has only spaces or new lines to be regarded as valid. This is done by checking if the trimmed version of the string is valid. --- validation/validation_test.go | 6 ++++++ validation/validators.go | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/validation/validation_test.go b/validation/validation_test.go index ec65b6d0..d8e880df 100644 --- a/validation/validation_test.go +++ b/validation/validation_test.go @@ -35,6 +35,12 @@ func TestRequired(t *testing.T) { if valid.Required("", "string").Ok { t.Error("\"'\" string should be false") } + if valid.Required(" ", "string").Ok { + t.Error("\" \" string should be false") // For #2361 + } + if valid.Required("\n", "string").Ok { + t.Error("new line string should be false") // For #2361 + } if !valid.Required("astaxie", "string").Ok { t.Error("string should be true") } diff --git a/validation/validators.go b/validation/validators.go index 9b04c5ce..78b10373 100644 --- a/validation/validators.go +++ b/validation/validators.go @@ -18,6 +18,7 @@ import ( "fmt" "reflect" "regexp" + "strings" "time" "unicode/utf8" ) @@ -98,7 +99,7 @@ func (r Required) IsSatisfied(obj interface{}) bool { } if str, ok := obj.(string); ok { - return len(str) > 0 + return len(strings.TrimSpace(str)) > 0 } if _, ok := obj.(bool); ok { return true