github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/validate/matcher/isBlank.go (about) 1 package matcher 2 3 import ( 4 "github.com/isyscore/isc-gobase/constants" 5 "reflect" 6 "strconv" 7 "strings" 8 9 "github.com/isyscore/isc-gobase/logger" 10 ) 11 12 type IsBlankMatch struct { 13 BlackWhiteMatch 14 15 // 是否设置过isNil值 16 HaveSet int8 17 18 // 匹配空字符的值 19 IsBlank bool 20 } 21 22 func (isBlankMatch *IsBlankMatch) Match(parameterMap map[string]interface{}, _ any, field reflect.StructField, fieldValue any) bool { 23 if reflect.TypeOf(fieldValue).Kind() != field.Type.Kind() { 24 isBlankMatch.SetBlackMsg("属性 %v 的值不是字符类型", field.Name) 25 return false 26 } 27 28 if isBlankMatch.IsBlank { 29 if fieldValue == "" { 30 isBlankMatch.SetBlackMsg("属性 %v 的值为空字符", field.Name) 31 return true 32 } else { 33 isBlankMatch.SetWhiteMsg("属性 %v 的值为非空字符", field.Name) 34 return false 35 } 36 } else { 37 if fieldValue != "" { 38 isBlankMatch.SetBlackMsg("属性 %v 的值不为空", field.Name) 39 return true 40 } else { 41 isBlankMatch.SetWhiteMsg("属性 %v 的值为空字符", field.Name) 42 return false 43 } 44 } 45 } 46 47 func (isBlankMatch *IsBlankMatch) IsEmpty() bool { 48 return isBlankMatch.HaveSet == 0 49 } 50 51 func BuildIsBlankMatcher(objectTypeFullName string, fieldKind reflect.Kind, objectFieldName string, tagName string, subCondition string, errMsg string) { 52 if constants.MATCH != tagName { 53 return 54 } 55 56 if fieldKind == reflect.Slice { 57 return 58 } 59 60 if !strings.Contains(subCondition, constants.IsBlank) { 61 return 62 } 63 64 value := "true" 65 if strings.Contains(subCondition, constants.EQUAL) { 66 index := strings.Index(subCondition, "=") 67 value = strings.TrimSpace(subCondition[index+1:]) 68 } 69 70 if strings.EqualFold("true", value) || strings.EqualFold("false", value) { 71 var isBlank bool 72 if chgValue, err := strconv.ParseBool(value); err == nil { 73 isBlank = chgValue 74 } else { 75 logger.Error(err.Error()) 76 return 77 } 78 addMatcher(objectTypeFullName, objectFieldName, &IsBlankMatch{IsBlank: isBlank, HaveSet: 1}, errMsg, true) 79 } 80 }