From 57bd72506bdf4f20bbbd4acc6c29c47825129387 Mon Sep 17 00:00:00 2001 From: dylan Date: Tue, 31 Dec 2024 00:19:53 +0100 Subject: [PATCH] Fix validation logic and make code more readable --- cmd/web/handlers.go | 18 +++++++++++++----- internal/validator/validator.go | 4 ++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index 2b6a425..b9a7b38 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -68,11 +68,19 @@ func isRequestValid(r *createElectionRequestWithValidator) bool { r.CheckField(validator.After(r.ExpiresAt, time.Now()), "expiresAt", "must expire in a future date") r.CheckField(validator.GreaterThan(len(r.Choices), 1), "choices", "there must be more than 1 choice") - r.CheckField( - !(r.AreVotersKnown && r.MaxVoters < 1), - "maxVoters", - "must be greater than 0 when voters are known", - ) + if r.AreVotersKnown { + r.CheckField( + validator.GreaterThan(r.MaxVoters, 0), + "maxVoters", + "must be greater than 0 when voters are known", + ) + } else { + r.CheckField( + validator.GreaterThanOrEquals(r.MaxVoters, 0), + "maxVoters", + "must be a positive number", + ) + } return r.Valid() } diff --git a/internal/validator/validator.go b/internal/validator/validator.go index 170a5d0..d91f2d3 100644 --- a/internal/validator/validator.go +++ b/internal/validator/validator.go @@ -60,6 +60,10 @@ func GreaterThan(value int, n int) bool { return value > n } +func GreaterThanOrEquals(value int, n int) bool { + return value >= n +} + func After(value time.Time, n time.Time) bool { return value.After(n) }