Skip to content

Commit 410ca84

Browse files
committed
added ContainsOnly validator
1 parent 921cd8b commit 410ca84

File tree

4 files changed

+62
-1
lines changed

4 files changed

+62
-1
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ Count occurrences of a chars and compares it with required value.
5555
passwordValidator := validator.New(validator.ContainsAtLeast(5, "abcdefghijklmnopqrstuvwxyz", nil))
5656
~~~
5757

58+
### ContainsOnly
59+
60+
Check if password contains only selected chars.
61+
62+
~~~go
63+
passwordValidator := validator.New(validator.ContainsOnly("abcdefghijklmnopqrstuvwxyz", nil))
64+
~~~
65+
5866
### MaxLength
5967

6068
Check if password length is not greater that defined length.

TODO.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
* Unique
22
* NotSequential
3-
* NotContains or ContainsOnly

contains_only.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package validator
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"strings"
7+
)
8+
9+
// ContainsOnly returns a ValidateFunc that check if password contains only selected chars
10+
func ContainsOnly(chars string, customError error) ValidateFunc {
11+
return ValidateFunc(func(password string) error {
12+
bChars := []byte(chars)
13+
for _, char := range strings.Split(password, "") {
14+
bChar := []byte(char)[0]
15+
idx := bytes.IndexByte(bChars, bChar)
16+
if idx == -1 {
17+
if customError != nil {
18+
return customError
19+
}
20+
return fmt.Errorf("the password must contains only %s", chars)
21+
}
22+
}
23+
return nil
24+
})
25+
}

contains_only_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package validator
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
)
7+
8+
func ExampleContainsOnly() {
9+
passwordValidator := ContainsOnly("abcdefghijklmnopqrstuvwxyz", nil)
10+
fmt.Println(passwordValidator("password"))
11+
fmt.Println(passwordValidator("password0"))
12+
fmt.Println(passwordValidator("passWORD"))
13+
// Output:
14+
// <nil>
15+
// the password must contains only abcdefghijklmnopqrstuvwxyz
16+
// the password must contains only abcdefghijklmnopqrstuvwxyz
17+
}
18+
19+
func ExampleContainsOnly_customError() {
20+
err := errors.New("custom error message")
21+
passwordValidator := ContainsOnly("abcdefghijklmnopqrstuvwxyz", err)
22+
fmt.Println(passwordValidator("password"))
23+
fmt.Println(passwordValidator("password0"))
24+
fmt.Println(passwordValidator("passWORD"))
25+
// Output:
26+
// <nil>
27+
// custom error message
28+
// custom error message
29+
}

0 commit comments

Comments
 (0)