File tree Expand file tree Collapse file tree 4 files changed +62
-1
lines changed Expand file tree Collapse file tree 4 files changed +62
-1
lines changed Original file line number Diff line number Diff line change @@ -55,6 +55,14 @@ Count occurrences of a chars and compares it with required value.
55
55
passwordValidator := validator.New (validator.ContainsAtLeast (5 , " abcdefghijklmnopqrstuvwxyz" , nil ))
56
56
~~~
57
57
58
+ ### ContainsOnly
59
+
60
+ Check if password contains only selected chars.
61
+
62
+ ~~~ go
63
+ passwordValidator := validator.New (validator.ContainsOnly (" abcdefghijklmnopqrstuvwxyz" , nil ))
64
+ ~~~
65
+
58
66
### MaxLength
59
67
60
68
Check if password length is not greater that defined length.
Original file line number Diff line number Diff line change 1
1
* Unique
2
2
* NotSequential
3
- * NotContains or ContainsOnly
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments