github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/validate/matcher/regex.go (about) 1 package matcher 2 3 import ( 4 "fmt" 5 "github.com/isyscore/isc-gobase/constants" 6 "reflect" 7 "regexp" 8 "strings" 9 ) 10 11 type RegexMatch struct { 12 BlackWhiteMatch 13 14 Reg *regexp.Regexp 15 } 16 17 func (regexMatch *RegexMatch) Match(_ map[string]interface{}, _ any, field reflect.StructField, fieldValue any) bool { 18 if regexMatch.Reg.MatchString(fmt.Sprintf("%v", fieldValue)) { 19 regexMatch.SetBlackMsg("属性 %v 的值 %v 命中禁用的正则表达式 %v ", field.Name, fieldValue, regexMatch.Reg.String()) 20 return true 21 } else { 22 regexMatch.SetWhiteMsg("属性 %v 的值 %v 没命中只允许的正则表达式 %v ", field.Name, fieldValue, regexMatch.Reg.String()) 23 } 24 return false 25 } 26 27 func (regexMatch *RegexMatch) IsEmpty() bool { 28 return regexMatch.Reg == nil 29 } 30 31 func BuildRegexMatcher(objectTypeFullName string, fieldKind reflect.Kind, objectFieldName string, tagName string, subCondition string, errMsg string) { 32 if constants.MATCH != tagName { 33 return 34 } 35 36 if fieldKind == reflect.Slice { 37 return 38 } 39 if !strings.Contains(subCondition, constants.Regex) || !strings.Contains(subCondition, constants.EQUAL) { 40 return 41 } 42 43 index := strings.Index(subCondition, "=") 44 value := subCondition[index+1:] 45 46 reg, err := regexp.Compile(value) 47 if err != nil { 48 return 49 } 50 addMatcher(objectTypeFullName, objectFieldName, &RegexMatch{Reg: reg}, errMsg, true) 51 }