Debian Codegraph @

validate.go

raw symbols SCIP
1 package huh
2
3 import (
4 "fmt"
5 "unicode/utf8"
6 )
7
8 // ValidateNotEmpty checks if the input is not empty.
9 func ValidateNotEmpty() func(s string) error {
10 return func(s string) error {
11 if err := ValidateMinLength(1)(s); err != nil {
12 return fmt.Errorf("input cannot be empty")
13 }
14 return nil
15 }
16 }
17
18 // ValidateMinLength checks if the length of the input is at least min.
19 func ValidateMinLength(v int) func(s string) error {
20 return func(s string) error {
21 if utf8.RuneCountInString(s) < v {
22 return fmt.Errorf("input must be at least %d characters long", v)
23 }
24 return nil
25 }
26 }
27
28 // ValidateMaxLength checks if the length of the input is at most max.
29 func ValidateMaxLength(v int) func(s string) error {
30 return func(s string) error {
31 if utf8.RuneCountInString(s) > v {
32 return fmt.Errorf("input must be at most %d characters long", v)
33 }
34 return nil
35 }
36 }
37
38 // ValidateLength checks if the length of the input is within the specified range.
39 func ValidateLength(minl, maxl int) func(s string) error {
40 return func(s string) error {
41 if err := ValidateMinLength(minl)(s); err != nil {
42 return err
43 }
44 return ValidateMaxLength(maxl)(s)
45 }
46 }
47
48 // ValidateOneOf checks if a string is one of the specified options.
49 func ValidateOneOf(options ...string) func(string) error {
50 validOptions := make(map[string]struct{})
51 for _, option := range options {
52 validOptions[option] = struct{}{}
53 }
54
55 return func(value string) error {
56 if _, ok := validOptions[value]; !ok {
57 return fmt.Errorf("invalid option: %s", value)
58 }
59 return nil
60 }
61 }