Skip to content

Commit

Permalink
slug: Add more validations to IsSlug
Browse files Browse the repository at this point in the history
The new validations are for empty string, _- as prefix or sufix of the slug and MaxLength validation if setted
  • Loading branch information
xescugc authored and matrixik committed Aug 22, 2017
1 parent a1294ed commit e9f42fa
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
9 changes: 8 additions & 1 deletion slug.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,16 @@ func smartTruncate(text string) string {

// IsSlug returns True if provided text does not contain white characters,
// punctuation, all letters are lower case and only from ASCII range.
// It could contain `-` and `_`.
// It could contain `-` and `_` but not at the beginning or end of the text.
// It should be in range of the MaxLength var if specified.
// All output from slug.Make(text) should pass this test.
func IsSlug(text string) bool {
if text == "" ||
(MaxLength > 0 && len(text) > MaxLength) ||
text[0] == '-' || text[0] == '_' ||
text[len(text)-1] == '-' || text[len(text)-1] == '_' {
return false
}
for _, c := range text {
if (c < 'a' || c > 'z') && c != '-' && c != '_' && (c < '0' || c > '9') {
return false
Expand Down
14 changes: 14 additions & 0 deletions slug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ func TestSlugMakeSmartTruncate(t *testing.T) {
}

func TestIsSlug(t *testing.T) {
MaxLength = 0
type args struct {
text string
}
Expand All @@ -219,8 +220,13 @@ func TestIsSlug(t *testing.T) {
{"with -", args{"some-more"}, true},
{"with _", args{"some_more"}, true},
{"with numbers", args{"number-2"}, true},
{"empty string", args{""}, false},
{"upper case", args{"Some-more"}, false},
{"space", args{"some more"}, false},
{"starts with '-'", args{"-some"}, false},
{"ends with '-'", args{"some-"}, false},
{"starts with '_'", args{"_some"}, false},
{"ends with '_'", args{"some_"}, false},
{"outside ASCII", args{"Dobrosław Żybort"}, false},
{"outside ASCII –", args{"2000–2013"}, false},
{"smile ☺", args{"smile ☺"}, false},
Expand All @@ -232,6 +238,14 @@ func TestIsSlug(t *testing.T) {
}
})
}

t.Run("MaxLength", func(t *testing.T) {
MaxLength = 4
if got := IsSlug("012345"); got != false {
t.Errorf("IsSlug() = %v, want %v", got, false)
}
MaxLength = 0
})
}

func BenchmarkMakeShortAscii(b *testing.B) {
Expand Down

0 comments on commit e9f42fa

Please sign in to comment.