Skip to content

Commit 945903a

Browse files
author
列里
committed
validator.go : 新增支持正则校验。
verify.go : UUID的正则校验使用示例。
1 parent 5ffc56d commit 945903a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

server/utils/validator.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package utils
33
import (
44
"errors"
55
"reflect"
6+
"regexp"
67
"strconv"
78
"strings"
89
)
@@ -38,6 +39,15 @@ func NotEmpty() string {
3839
return "notEmpty"
3940
}
4041

42+
//@author: [zooqkl](https://github.com/zooqkl)
43+
//@function: RegexpMatch
44+
//@description: 正则校验 校验输入项是否满足正则表达式
45+
//@param: rule string
46+
//@return: string
47+
func RegexpMatch(rule string) string {
48+
return "regexp=" + rule
49+
}
50+
4151
//@author: [piexlmax](https://github.com/piexlmax)
4252
//@function: Lt
4353
//@description: 小于入参(<) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较
@@ -134,6 +144,10 @@ func Verify(st interface{}, roleMap Rules) (err error) {
134144
if isBlank(val) {
135145
return errors.New(tagVal.Name + "值不能为空")
136146
}
147+
case strings.Split(v, "=")[0] == "regexp":
148+
if !regexpMatch(strings.Split(v, "=")[1], val.String()) {
149+
return errors.New(tagVal.Name + "格式校验不通过")
150+
}
137151
case compareMap[strings.Split(v, "=")[0]]:
138152
if !compareVerify(val, v) {
139153
return errors.New(tagVal.Name + "长度或值不在合法范围," + v)
@@ -267,3 +281,7 @@ func compare(value interface{}, VerifyStr string) bool {
267281
return false
268282
}
269283
}
284+
285+
func regexpMatch(rule, matchStr string) bool {
286+
return regexp.MustCompile(rule).MatchString(matchStr)
287+
}

server/utils/verify.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,5 @@ var (
1414
AuthorityIdVerify = Rules{"AuthorityId": {NotEmpty()}}
1515
OldAuthorityVerify = Rules{"OldAuthorityId": {NotEmpty()}}
1616
ChangePasswordVerify = Rules{"Username": {NotEmpty()}, "Password": {NotEmpty()}, "NewPassword": {NotEmpty()}}
17-
SetUserAuthorityVerify = Rules{"UUID": {NotEmpty()}, "AuthorityId": {NotEmpty()}}
17+
SetUserAuthorityVerify = Rules{"UUID": {NotEmpty(), RegexpMatch("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}")}, "AuthorityId": {NotEmpty()}}
1818
)

0 commit comments

Comments
 (0)