lets-go:8.3 some validation

This commit is contained in:
tamsin johnson 2024-01-25 22:57:49 -08:00
parent 1931b047fc
commit 5316e01cce

View File

@ -5,6 +5,8 @@ import (
"fmt"
"net/http"
"strconv"
"strings"
"unicode/utf8"
"github.com/julienschmidt/httprouter"
"snippetbox.chaosfem.tw/internal/models"
@ -74,6 +76,27 @@ func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request
return
}
fieldErrors := make(map[string]string)
if strings.TrimSpace(title) == "" {
fieldErrors["title"] = "This field cannot be blank"
} else if utf8.RuneCountInString(title) > 100 {
fieldErrors["title"] = "This field cannot contain more than 100 characters"
}
if strings.TrimSpace(content) == "" {
fieldErrors["content"] = "This field cannot be blank"
}
if expires != 1 && expires != 7 && expires != 365 {
fieldErrors["expires"] = "This field must equal 1, 7 or 365"
}
if len(fieldErrors) > 0 {
fmt.Fprint(w, fieldErrors)
return
}
id, err := app.snippets.Insert(title, content, expires)
if err != nil {
app.serverError(w, r, err)