Skip to content

Latest commit

 

History

History
130 lines (92 loc) · 5.51 KB

File metadata and controls

130 lines (92 loc) · 5.51 KB

#4.2 Verification of inputs The most important principle in web development is that you cannot trust anything from user form, you have to verify all data before use them. You may know many websites are invaded by this problem which is simple but crucial.

There are two ways to verify form data that commonly used, the one is JavaScript verification in front-end, and another one is server verification in back-end. In this section, we are going to talk about the server verification in web development.

##Required fields Sometimes you ask users to input some fields but they don't, for example we need user name in previous section. You can use function len to get length of field to make sure users input this information.

if len(r.Form["username"][0])==0{
	// code for empty field
}

r.Form uses different treatments of different types of form elements when they are blanks. For empty text box, text area and file upload, it returns empty string; for radio button and check box, it doesn't even create corresponding items, and you will get errors if you try to access it. Therefore, we'd better use r.Form.Get() to get filed values because it always returns empty if the value does not exist. On the other hand, r.Form.Get() can only get one field value every time, so you need to use r.Form to get values in map.

##Numbers Sometimes you only need numbers for the field value. For example, you need age of users, like 50 or 10, instead of "old enough" or "young man". If we need positive numbers, we can convert to int type first and process them.

getint,err:=strconv.Atoi(r.Form.Get("age"))
if err!=nil{
	// error occurs when convert to number, it may not a number
}

// check range of number
if getint >100 {
	// too big
}

Another way to do this is using regular expression.

if m, _ := regexp.MatchString("^[0-9]+$", r.Form.Get("age")); !m {
	return false
}

For high performance purpose, regular expression is not an efficient way, but simple regular expression is fast enough. If you know regular expression before, you should it's a very convenient way to verify data. Notice that Go uses RE2, all UTF-8 characters are supported.

##Chinese Sometimes we need users to input their Chinese name, we have to verify they use all Chinese rather than random characters. For Chinese verification, regular expression is the only way.

if m, _ := regexp.MatchString("^[\\x{4e00}-\\x{9fa5}]+$", r.Form.Get("realname")); !m {
	return false
}

##English letters Sometimes we need users to input English letters. For example, we need someone's English name, like astaxie instead of asta谢. We can easily use regular expression to do verification.

if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m {
	return false
}

##E-mail address If you want to know if users input valid E-mail address, you can use following regular expression:

if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([a-z]{2,4})$`, r.Form.Get("email")); !m {
	fmt.Println("no")
}else{
	fmt.Println("yes")
}

##Drop down list When we need item in our drop down list, but we get some values that are made by hackers, how can we prevent it?

Suppose we have following <select>:

<select name="fruit">
<option value="apple">apple</option>
<option value="pear">pear</option>
<option value="banane">banane</option>
</select>

Then, we use following way to verify:

slice:=[]string{"apple","pear","banane"}

for _, v := range slice {
	if v == r.Form.Get("fruit") {
    	return true
	}
}
return false

All functions I showed above are in my open source project for operating slice and map: https://github.com/astaxie/beeku

##Radio buttons If we want to know the user is male or female, we may use a radio button, return 1 for male and 2 for female. However, there is a little boy is reading book about HTTP, and send to you 3, will your program have exception? So we need to use same way for drop down list to make sure all values are expected.

<input type="radio" name="gender" value="1">Male
<input type="radio" name="gender" value="2">Female

And we use following code to do verification:

slice:=[]int{1,2}

for _, v := range slice {
	if v == r.Form.Get("gender") {
    	return true
	}
}
return false

##Check boxes Suppose there are some check boxes for users' interests, and you don't want extra values as well.

<input type="checkbox" name="interest" value="football">Football
<input type="checkbox" name="interest" value="basketball">Basketball
<input type="checkbox" name="interest" value="tennis">Tennis

Here is a little bit different in verification between radio buttons and check boxes because we get a slice from check boxes.

slice:=[]string{"football","basketball","tennis"}
a:=Slice_diff(r.Form["interest"],slice)
if a == nil{
	return true
}

return false 

##Date and time Suppose you want to make users input valid date or time. Go has package time to convert year, month, day to corresponding time, then it's easy to check it.

t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
fmt.Printf("Go launched at %s\n", t.Local())

After you had time, you can use package time for more operations depend on your purposes.

We talked about some common form data verification in server side, I hope you understand more about data verification in Go, especially how to use regular expression.

##Links