diff --git a/cmd/web/handlers.go b/cmd/web/handlers.go index 326c649..9b9880c 100644 --- a/cmd/web/handlers.go +++ b/cmd/web/handlers.go @@ -15,6 +15,34 @@ type createElectionRequestWithValidator struct { validator.Validator } +func (r *createElectionRequestWithValidator) isValid() bool { + r.CheckField(validator.NotBlank(r.Name), "name", "must not be blank") + r.CheckField(validator.GreaterThan(r.Tokens, 0), "tokens", "must be greater than 0") + 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(validator.UniqueValues(r.Choices), "choices", "must not contain duplicate values") + + for _, choice := range r.Choices { + r.CheckField(validator.NotBlank(choice), "choice", "must not be blank") + } + + 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() +} + func (app *application) createElection(w http.ResponseWriter, r *http.Request) { var request createElectionRequestWithValidator @@ -64,34 +92,6 @@ func (app *application) createElection(w http.ResponseWriter, r *http.Request) { w.Write(res) } -func (r *createElectionRequestWithValidator) isValid() bool { - r.CheckField(validator.NotBlank(r.Name), "name", "must not be blank") - r.CheckField(validator.GreaterThan(r.Tokens, 0), "tokens", "must be greater than 0") - 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(validator.UniqueValues(r.Choices), "choices", "must not contain duplicate values") - - for _, choice := range r.Choices { - r.CheckField(validator.NotBlank(choice), "choice", "must not be blank") - } - - 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() -} - func randomVoterIdentity() string { const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" b := make([]byte, 16)