Server side form validation 2

This commit is contained in:
Muyao CHEN 2024-06-30 19:35:59 +02:00
parent 8394832428
commit 8be6ba7119
4 changed files with 52 additions and 3 deletions

View File

@ -22,5 +22,14 @@ func New(data url.Values) *Form {
// Has checks if form field is in post and not emtpy // Has checks if form field is in post and not emtpy
func (f *Form) Has(field string, r *http.Request) bool { func (f *Form) Has(field string, r *http.Request) bool {
x := r.Form.Get(field) 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
} }

View File

@ -76,6 +76,33 @@ func (m *Repository) MakeReservation(w http.ResponseWriter, r *http.Request) {
// PostMakeReservation is the make reservation page post handler // PostMakeReservation is the make reservation page post handler
func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request) { 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 // Availability is the search for availability page handler

View File

@ -0,0 +1,9 @@
package models
// Reservation holds Reservation data
type Reservation struct {
FirstName string
LastName string
Email string
Phone string
}

View File

@ -8,10 +8,14 @@
<!-- <form method="post" action="" class="needs-validation" novalidate> --> <!-- <form method="post" action="" class="needs-validation" novalidate> -->
<form method="post" action="" class="" novalidate> <form method="post" action="" class="" novalidate>
<input type="hidden" name="csrf_token" value="{{.CSRFToken}}"> <input type="hidden" name="csrf_token" value="{{.CSRFToken}}">
<div class="form-group mt-5"> <div class="form-group mt-5">
<label for="first_name">First name:</label> <label for="first_name">First name:</label>
<input type="text" name="first_name" id="first_name" class="form-control" required {{with .Form.Errors.Get "first_name"}}
autocomplete="off"> <label class="text-danger">{{.}}</label>
{{end}}
<input type="text" name="first_name" id="first_name" class="form-control {{with .Form.Errors.Get "first_name"}} is-invalid {{end}}"
required autocomplete="off">
</div> </div>
<div class="form-group mt-5"> <div class="form-group mt-5">
<label for="last_name">Last name:</label> <label for="last_name">Last name:</label>