41

GO随笔-表单验证

 5 years ago
source link: https://studygolang.com/articles/16587?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

新发现: r.Form 里面包含了所有请求的参数,比如URL中query-string、POST的数据、PUT的数据,所有当你在URL的query-string字段和POST冲突时,会保存成一个slice,里面存储了多个值

举个例子:

<form action="/login?username=go" method="post">//get方法传递username=go
用户名:<input type="text" name="username">//用post方法传递username

在提交表单后,打印 r.Form

fmt.Println(r.Form);

得到

map[username:[postname go]

发生冲突的字段,值会被保存成为slice。

在取值的时候有两种方法。

r.Form 可以取到键所对应的全部值。但如果键不存在则会报错。一般单选框或复选框,在不选中的情况下,form表单根本不会提交这些字段,所以很容易出现 r.Form 获取键不存在的字段。

r.Form.GET 只能够拿到字段中的第一个值。如果键不存在,不会报错,会返回空值。

对比不难发现,一般单选框和复选框等字段需要 r.Form.GET 方法获取,而会出现多值的字段则需要用 r.Form 的方式获取。

言归正传,这次想说一些关于表单验证的方法。表单验证一般前端后端都会做,不过区别是,“前端防君子,后端防小人”。

必填字段

if len(r.Form["username"][0])==0{
    //为空的处理
}

数字

getint,err:=strconv.Atoi(r.Form.Get("age"))//字符串转整
if err!=nil{
    //数字转化出错了,那么可能就不是数字
}

//接下来就可以判断这个数字的大小范围了
if getint >100 {
    //太大了
}

或是使用正则

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

还有很多验证,都有不止一种方法能够达到验证效果,不再一一赘述了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK