One of the principles of developing the web is that you cannot trust any information entered by the user, so it is very important to validate and filter the user's input.
Required fields
if len(r.Form["username"][0])==0{ // handle empty }
number
getint,err:=strconv.Atoi(r.Form.Get("age")) if err!=nil{ //The number conversion is wrong, then it may not be a number } // Next, you can determine the size range of this number if getint >100 { //too big }
if m, _ := regexp.MatchString("^[0-9]+$", r.Form.Get("age")); !m { return false }
Convert numbers and regular matches
For performance, avoid regulars, regulars will have a matching time, multiple matching speeds will be slow, but it does not matter if the server is strong.
match Chinese
if m, _ := regexp.MatchString("^\\p{Han}+$", r.Form.Get("realname")); !m { return false }
match english
if m, _ := regexp.MatchString("^[a-zA-Z]+$", r.Form.Get("engname")); !m { return false }
match email
if m, _ := regexp.MatchString(`^([\w\.\_]{2,10})@(\w{1,}).([az]{2,4})$`, r.Form.Get("email")); !m { //Matches 2 to 10 alphanumeric underscores and dots, plus @ and then matches at least one alphanumeric underscore, plus . matches the letters az (at least 2 to 4) fmt.Println("no") }else{ fmt.Println("yes") }
phone number
if m, _ := regexp.MatchString(`^(1[3|4|5|8][0-9]\d{4,8})$`, r.Form.Get("mobile")); !m { return false }
Judgment of drop-down menu
slice:=[]string{"haha","ccc","bca"} //Create a slice v := r.Form.Get("fruit") for _, item := range slice { if item == v { return true } } return false
checkbox to select different
slice:=[]string{"football","basketball","tennis"} a:=Slice_diff(r.Form["interest"],slice) if a == nil{ return true } return false
ID number
//Verify 15 ID cards, 15 digits are all numbers if m, _ := regexp.MatchString(`^(\d{15})$`, r.Form.Get("usercard")); !m { return false } //Verify the 18-digit ID card, the first 17 digits of the 18 digits are numbers, and the last digit is the check digit, which may be a number or the character X. if m, _ := regexp.MatchString(`^(\d{17})([0-9]|X)$`, r.Form.Get("usercard")); !m { return false }