From 89f16412e84d222388320f4ff88e0779706945f5 Mon Sep 17 00:00:00 2001 From: Jannis Mattheis Date: Sun, 8 Apr 2018 14:33:50 +0200 Subject: [PATCH] [#34] Add error messages for min and max --- error/handler.go | 4 ++++ error/handler_test.go | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/error/handler.go b/error/handler.go index 1447310..dd23e38 100644 --- a/error/handler.go +++ b/error/handler.go @@ -49,6 +49,10 @@ func validationErrorToText(e *validator.FieldError) string { switch e.Tag { case "required": return fmt.Sprintf("Field '%s' is required", fieldName) + case "max": + return fmt.Sprintf("Field '%s' must be less or equal to %s", fieldName, e.Param) + case "min": + return fmt.Sprintf("Field '%s' must be more or equal to %s", fieldName, e.Param) } return fmt.Sprintf("Field '%s' is not valid", fieldName) } diff --git a/error/handler_test.go b/error/handler_test.go index c764adb..ab060a7 100644 --- a/error/handler_test.go +++ b/error/handler_test.go @@ -49,6 +49,8 @@ func TestDefaultErrorBadRequest(t *testing.T) { type testValidate struct { Username string `json:"username" binding:"required"` Mail string `json:"mail" binding:"email"` + Age int `json:"age" binding:"max=100"` + Limit int `json:"limit" binding:"min=50"` } func TestValidationError(t *testing.T) { @@ -57,7 +59,7 @@ func TestValidationError(t *testing.T) { ctx, _ := gin.CreateTestContext(rec) ctx.Request = httptest.NewRequest("GET", "/uri", nil) - assert.NotNil(t, ctx.Bind(&testValidate{})) + assert.NotNil(t, ctx.Bind(&testValidate{Age: 150, Limit: 20})) Handler()(ctx) err := new(model.Error) @@ -67,6 +69,8 @@ func TestValidationError(t *testing.T) { assert.Equal(t, 400, err.ErrorCode) assert.Contains(t, err.ErrorDescription, "Field 'username' is required") assert.Contains(t, err.ErrorDescription, "Field 'mail' is not valid") + assert.Contains(t, err.ErrorDescription, "Field 'age' must be less or equal to 100") + assert.Contains(t, err.ErrorDescription, "Field 'limit' must be more or equal to 50") } func assertJSONResponse(t *testing.T, rec *httptest.ResponseRecorder, code int, json string) {