Browse Source

validator.go : 新增支持正则校验。
verify.go : UUID的正则校验使用示例。

列里 3 years ago
parent
commit
945903a8bb
2 changed files with 19 additions and 1 deletions
  1. 18 0
      server/utils/validator.go
  2. 1 1
      server/utils/verify.go

+ 18 - 0
server/utils/validator.go

@@ -3,6 +3,7 @@ package utils
 import (
 	"errors"
 	"reflect"
+	"regexp"
 	"strconv"
 	"strings"
 )
@@ -38,6 +39,15 @@ func NotEmpty() string {
 	return "notEmpty"
 }
 
+//@author: [zooqkl](https://github.com/zooqkl)
+//@function: RegexpMatch
+//@description: 正则校验 校验输入项是否满足正则表达式
+//@param:  rule string
+//@return: string
+func RegexpMatch(rule string) string {
+	return "regexp=" + rule
+}
+
 //@author: [piexlmax](https://github.com/piexlmax)
 //@function: Lt
 //@description: 小于入参(<) 如果为string array Slice则为长度比较 如果是 int uint float 则为数值比较
@@ -134,6 +144,10 @@ func Verify(st interface{}, roleMap Rules) (err error) {
 					if isBlank(val) {
 						return errors.New(tagVal.Name + "值不能为空")
 					}
+				case strings.Split(v, "=")[0] == "regexp":
+					if !regexpMatch(strings.Split(v, "=")[1], val.String()) {
+						return errors.New(tagVal.Name + "格式校验不通过")
+					}
 				case compareMap[strings.Split(v, "=")[0]]:
 					if !compareVerify(val, v) {
 						return errors.New(tagVal.Name + "长度或值不在合法范围," + v)
@@ -267,3 +281,7 @@ func compare(value interface{}, VerifyStr string) bool {
 		return false
 	}
 }
+
+func regexpMatch(rule, matchStr string) bool {
+	return regexp.MustCompile(rule).MatchString(matchStr)
+}

+ 1 - 1
server/utils/verify.go

@@ -14,5 +14,5 @@ var (
 	AuthorityIdVerify      = Rules{"AuthorityId": {NotEmpty()}}
 	OldAuthorityVerify     = Rules{"OldAuthorityId": {NotEmpty()}}
 	ChangePasswordVerify   = Rules{"Username": {NotEmpty()}, "Password": {NotEmpty()}, "NewPassword": {NotEmpty()}}
-	SetUserAuthorityVerify = Rules{"UUID": {NotEmpty()}, "AuthorityId": {NotEmpty()}}
+	SetUserAuthorityVerify = Rules{"UUID": {NotEmpty(), RegexpMatch("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}")}, "AuthorityId": {NotEmpty()}}
 )