Radio button validation


(Nadia Kenawi) #1

Hola,
I tried to do radio validation.
I followed this tutorial https://astaxie.gitbooks.io/build-web-application-with-golang/en/04.2.html
Only problem that it gave me an error when i did if and i didn’t understand why.
main.go

func send(w http.ResponseWriter, r *http.Request) {
gender:= []int{1, 2, 3}
msg := &Message{
Name: r.FormValue(“name”),
Surname: r.FormValue(“surname”),
BDay: r.FormValue(“bday”),
Gender: r.FormValue(“gender”),
}

for _, v := range gender{
if v == r.Form.Get(“gender”) {
msg.Errors[“Gender”] = “Please choose your Gender”

}
}

if msg.Validate() == false {
	render(w, "templates/index.html", msg)
	return
}
// Send message in an email
// Redirect to confirmation page

}

Actually, the for should to be another page message.go, ma i don’t have r *http.Request, i thought to do it into the main.go

message.go

type Message struct {
Name string
Surname string
BDay string
Gender string
City string
Errors map[string]string
}

func (msg *Message) Validate() bool {

msg.Errors = make(map[string]string)
if strings.TrimSpace(msg.Name) == "" {
	msg.Errors["Name"] = "Please write your Name"
}
if strings.TrimSpace(msg.Surname) == "" {
	msg.Errors["Surname"] = "Please write your Surname"
}
//Gestire la data
if strings.TrimSpace(msg.BDay) == "" {
	msg.Errors["BDay"] = "Please select your BDay"
}

//Fare il radio button

if strings.TrimSpace(msg.City) == "" {
	msg.Errors["City"] = "Please write your City"
}

return len(msg.Errors) == 0

}


(mathew) #2

Firstly, put your code somewhere where it’ll be formatted nicely (Github Gist, go playground, etc), or use triple backticks to make sure it’s formatted here.

Secondly, you didn’t tell us what the error was.

Thirdly, it looks as if you’re not actually parsing the form values with r.ParseForm() before trying to examine them.


(Curtis Allyn Green) #3

You have some good points, honestly the backticks would be preferrable I think to sharing a repo, playground examples are great. However chastising the way someone does something valid within the language isn’t so great. The FormValue method of a Request type can be called without calling ParseForm or ParseMultipartForm, because those methods will automatically be called by FormValue if needed: https://godoc.org/net/http#Request.FormValue


(mathew) #4

I wasn’t “chastising the way someone does something valid within the language”. I made no code style comments at all, I simply suggested ParseForm because I was under the impression that it was necessary.


(Curtis Allyn Green) #5

I’m sorry, sounded bad when I read it in my head. I also assumed you already knew about it.


(system) #6

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.