This commit is contained in:
lbenedar
2026-03-05 15:59:44 +03:00
parent 3bd8a8e1c7
commit c2883b9916
2 changed files with 59 additions and 24 deletions

View File

@@ -6,18 +6,17 @@ import (
"fmt"
"net/http"
"strconv"
"strings"
"unicode/utf8"
"gitea.local.lab/Lbenedar/snippetbox/internal/models"
"gitea.local.lab/Lbenedar/snippetbox/internal/validator"
"github.com/julienschmidt/httprouter"
)
type snippetCreateForm struct {
Title string
Content string
Expires int
FieldErrors map[string]string
Title string
Content string
Expires int
validator.Validator
}
func (app *application) render(w http.ResponseWriter, status int, page string, data *templateData) {
@@ -102,27 +101,17 @@ func (app *application) snippetCreatePost(w http.ResponseWriter, r *http.Request
}
form := snippetCreateForm{
Title: r.PostForm.Get("title"),
Content: r.PostForm.Get("content"),
Expires: expires,
FieldErrors: map[string]string{},
Title: r.PostForm.Get("title"),
Content: r.PostForm.Get("content"),
Expires: expires,
}
if strings.TrimSpace(form.Title) == "" {
form.FieldErrors["title"] = "This field cannot be blank"
} else if utf8.RuneCountInString(form.Title) > 100 {
form.FieldErrors["title"] = "This field cannot be more than 100 character long"
}
form.CheckField(validator.NotBlank(form.Title), "title", "This field cannot be blank")
form.CheckField(validator.MaxChars(form.Title, 100), "title", "This field cannot be more than 100 character long")
form.CheckField(validator.NotBlank(form.Content), "content", "This field cannot be blank")
form.CheckField(validator.PermittedInt(form.Expires, 1, 7, 365), "expires", "This field must equal 1, 7 and 365")
if strings.TrimSpace(form.Content) == "" {
form.FieldErrors["content"] = "This field cannot be blank"
}
if form.Expires != 1 && form.Expires != 7 && form.Expires != 365 {
form.FieldErrors["expires"] = "This field must equal 1, 7 and 365"
}
if len(form.FieldErrors) > 0 {
if !form.Valid() {
data := app.newTemplateData(r)
data.Form = form
app.render(w, http.StatusUnprocessableEntity, "create.tmpl", data)