Skip to content

Commit b29e594

Browse files
committed
added Unique validator
1 parent 410ca84 commit b29e594

File tree

4 files changed

+57
-1
lines changed

4 files changed

+57
-1
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,11 @@ Check if password starts with one of letter.
112112
~~~go
113113
passwordValidator := validator.New(validator.StartsWith("abcdefghijklmnopqrstuvwxyz", nil))
114114
~~~
115+
116+
### Unique
117+
118+
Check if password contains only unique chars.
119+
120+
~~~go
121+
passwordValidator := validator.New(validator.Unique(nil))
122+
~~~

TODO.md

-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
1-
* Unique
21
* NotSequential

unique.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package validator
2+
3+
import (
4+
"errors"
5+
"strings"
6+
)
7+
8+
// Unique returns ValidateFunc that validate whether the password has only unique chars
9+
func Unique(customError error) ValidateFunc {
10+
return ValidateFunc(func(password string) error {
11+
runes := []rune(password)
12+
for idx := range runes {
13+
if strings.LastIndexFunc(password, func(r rune) bool {
14+
return r == runes[idx]
15+
}) != idx {
16+
if customError != nil {
17+
return customError
18+
}
19+
return errors.New("the password must contains unique chars")
20+
}
21+
}
22+
return nil
23+
})
24+
}

unique_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package validator
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
)
7+
8+
func ExampleUnique() {
9+
passwordValidator := Unique(nil)
10+
fmt.Println(passwordValidator("bui87j"))
11+
fmt.Println(passwordValidator("qwerte"))
12+
// Output:
13+
// <nil>
14+
// the password must contains unique chars
15+
}
16+
17+
func ExampleUnique_customError() {
18+
err := errors.New("custom error message")
19+
passwordValidator := Unique(err)
20+
fmt.Println(passwordValidator("bui87j"))
21+
fmt.Println(passwordValidator("qwerte"))
22+
// Output:
23+
// <nil>
24+
// custom error message
25+
}

0 commit comments

Comments
 (0)