Skip to content

Commit

Permalink
Merge pull request #299 from okisetiawan0101/new-string-length-tag
Browse files Browse the repository at this point in the history
New string length validator
  • Loading branch information
asaskevich committed Jan 8, 2020
2 parents 7ec8f5a + 2844878 commit bf6f341
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
18 changes: 11 additions & 7 deletions types.go
Expand Up @@ -59,13 +59,15 @@ var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{

// ParamTagMap is a map of functions accept variants parameters
var ParamTagMap = map[string]ParamValidator{
"length": ByteLength,
"range": Range,
"runelength": RuneLength,
"stringlength": StringLength,
"matches": StringMatches,
"in": isInRaw,
"rsapub": IsRsaPub,
"length": ByteLength,
"range": Range,
"runelength": RuneLength,
"stringlength": StringLength,
"matches": StringMatches,
"in": IsInRaw,
"rsapub": IsRsaPub,
"minstringlength": MinStringLength,
"maxstringlength": MaxStringLength,
}

// ParamTagRegexMap maps param tags to their respective regexes.
Expand All @@ -77,6 +79,8 @@ var ParamTagRegexMap = map[string]*regexp.Regexp{
"in": regexp.MustCompile(`^in\((.*)\)`),
"matches": regexp.MustCompile(`^matches\((.+)\)$`),
"rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"),
"minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"),
"maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"),
}

type customTypeTagMap struct {
Expand Down
26 changes: 25 additions & 1 deletion validator.go
Expand Up @@ -1127,6 +1127,30 @@ func StringLength(str string, params ...string) bool {
return false
}

// MinStringLength check string's minimum length (including multi byte strings)
func MinStringLength(str string, params ...string) bool {

if len(params) == 1 {
strLength := utf8.RuneCountInString(str)
min, _ := ToInt(params[0])
return strLength >= int(min)
}

return false
}

// MaxStringLength check string's maximum length (including multi byte strings)
func MaxStringLength(str string, params ...string) bool {

if len(params) == 1 {
strLength := utf8.RuneCountInString(str)
max, _ := ToInt(params[0])
return strLength <= int(max)
}

return false
}

// Range check string's length
func Range(str string, params ...string) bool {
if len(params) == 2 {
Expand All @@ -1139,7 +1163,7 @@ func Range(str string, params ...string) bool {
return false
}

func isInRaw(str string, params ...string) bool {
func IsInRaw(str string, params ...string) bool {
if len(params) == 1 {
rawParams := params[0]

Expand Down

0 comments on commit bf6f341

Please sign in to comment.