[#34] Add error messages for min and max

This commit is contained in:
Jannis Mattheis 2018-04-08 14:33:50 +02:00 committed by Jannis Mattheis
parent 1831b6078f
commit 89f16412e8
2 changed files with 9 additions and 1 deletions

View File

@ -49,6 +49,10 @@ func validationErrorToText(e *validator.FieldError) string {
switch e.Tag { switch e.Tag {
case "required": case "required":
return fmt.Sprintf("Field '%s' is required", fieldName) 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) return fmt.Sprintf("Field '%s' is not valid", fieldName)
} }

View File

@ -49,6 +49,8 @@ func TestDefaultErrorBadRequest(t *testing.T) {
type testValidate struct { type testValidate struct {
Username string `json:"username" binding:"required"` Username string `json:"username" binding:"required"`
Mail string `json:"mail" binding:"email"` 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) { func TestValidationError(t *testing.T) {
@ -57,7 +59,7 @@ func TestValidationError(t *testing.T) {
ctx, _ := gin.CreateTestContext(rec) ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest("GET", "/uri", nil) 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) Handler()(ctx)
err := new(model.Error) err := new(model.Error)
@ -67,6 +69,8 @@ func TestValidationError(t *testing.T) {
assert.Equal(t, 400, err.ErrorCode) assert.Equal(t, 400, err.ErrorCode)
assert.Contains(t, err.ErrorDescription, "Field 'username' is required") 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 '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) { func assertJSONResponse(t *testing.T, rec *httptest.ResponseRecorder, code int, json string) {