diff --git a/go.mod b/go.mod index 269c6fe..e32e8a3 100644 --- a/go.mod +++ b/go.mod @@ -7,3 +7,5 @@ require github.com/go-chi/chi/v5 v5.0.14 require github.com/justinas/nosurf v1.1.1 require github.com/alexedwards/scs/v2 v2.8.0 + +require github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect diff --git a/go.sum b/go.sum index 3ac5c47..02c3a52 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/alexedwards/scs/v2 v2.8.0 h1:h31yUYoycPuL0zt14c0gd+oqxfRwIj6SOjHdKRZxhEw= github.com/alexedwards/scs/v2 v2.8.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= github.com/go-chi/chi/v5 v5.0.14 h1:PyEwo2Vudraa0x/Wl6eDRRW2NXBvekgfxyydcM0WGE0= github.com/go-chi/chi/v5 v5.0.14/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= github.com/justinas/nosurf v1.1.1 h1:92Aw44hjSK4MxJeMSyDa7jwuI9GR2J/JCQiaKvXXSlk= diff --git a/internal/forms/forms.go b/internal/forms/forms.go index bb8be67..9fbf3cc 100644 --- a/internal/forms/forms.go +++ b/internal/forms/forms.go @@ -5,6 +5,8 @@ import ( "net/http" "net/url" "strings" + + "github.com/asaskevich/govalidator" ) // Form creates a custom form struct, embeds a url.Values object @@ -51,3 +53,11 @@ func (f *Form) MinLength(field string, length int, r *http.Request) bool { } return true } + +// IsEmail checks the email address +func (f *Form) IsEmail(field string, r *http.Request) { + value := r.Form.Get(field) + if !govalidator.IsEmail(value) { + f.Errors.Add(field, "Invalid email address") + } +} diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index 2b28efa..5f7d15c 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -101,6 +101,7 @@ func (m *Repository) PostMakeReservation(w http.ResponseWriter, r *http.Request) form.Required("first_name", "last_name", "email") form.MinLength("first_name", 2, r) + form.IsEmail("email", r) if !form.Valid() { data := make(map[string]interface{})