diff --git a/internal/forms/forms.go b/internal/forms/forms.go index c1a03c6..0a2116d 100644 --- a/internal/forms/forms.go +++ b/internal/forms/forms.go @@ -22,5 +22,14 @@ func New(data url.Values) *Form { // Has checks if form field is in post and not emtpy func (f *Form) Has(field string, r *http.Request) bool { x := r.Form.Get(field) - return x != "" + if x == "" { + f.Errors.Add(field, "This field cannot be blank") + return false + } + return true +} + +// Valid returns true if there are no errors, otherwise false +func (f *Form) Valid() bool { + return len(f.Errors) == 0 } diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index 41dd0ba..1bf53fe 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -76,6 +76,33 @@ func (m *Repository) MakeReservation(w http.ResponseWriter, r *http.Request) { // PostMakeReservation is the make reservation page post handler func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request) { + err := r.ParseForm() + if err != nil { + log.Println(err) + return + } + + reservation := models.Reservation{ + FirstName: r.Form.Get("first_name"), + LastName: r.Form.Get("last_name"), + Email: r.Form.Get("email"), + Phone: r.Form.Get("phone"), + } + + form := forms.New(r.PostForm) + + form.Has("first_name", r) + + if !form.Valid() { + data := make(map[string]interface{}) + data["reservation"] = reservation + + render.RenderTemplate(w, r, "make-reservation.page.tmpl", &models.TemplateData{ + Data: data, + Form: form, + }) + return + } } // Availability is the search for availability page handler diff --git a/internal/models/models.go b/internal/models/models.go new file mode 100644 index 0000000..65da1a6 --- /dev/null +++ b/internal/models/models.go @@ -0,0 +1,9 @@ +package models + +// Reservation holds Reservation data +type Reservation struct { + FirstName string + LastName string + Email string + Phone string +} diff --git a/templates/make-reservation.page.tmpl b/templates/make-reservation.page.tmpl index 8005a68..220945d 100644 --- a/templates/make-reservation.page.tmpl +++ b/templates/make-reservation.page.tmpl @@ -8,10 +8,14 @@
+
- + {{with .Form.Errors.Get "first_name"}} + + {{end}} +