-
Notifications
You must be signed in to change notification settings - Fork 11
/
validation.go
60 lines (54 loc) · 1.59 KB
/
validation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package validation
import (
"fmt"
"github.com/AlecAivazis/survey/v2"
uuid "github.com/google/uuid"
"os"
"reflect"
)
// NotEquals requires that the string does not equal any of the specified values
func NotEquals(stringsToCheck []string, errorMessage string) survey.Validator {
// return a validator to perform the check
return func(val interface{}) error {
if str, ok := val.(string); ok {
for _, v := range stringsToCheck {
if str == v {
return fmt.Errorf("%s", errorMessage)
}
}
} else {
// otherwise we cannot convert the value into a string and cannot perform check
return fmt.Errorf("cannot check value on response of type %v", reflect.TypeOf(val).Name())
}
// the input is fine
return nil
}
}
// IsUuid requires that the string is a valid UUID
func IsUuid(val interface{}) error {
if str, ok := val.(string); ok {
if _, err := uuid.Parse(str); err != nil {
return fmt.Errorf("not a valid UUID")
}
} else {
// otherwise we cannot convert the value into a string and cannot perform check
return fmt.Errorf("cannot check value on response of type %v", reflect.TypeOf(val).Name())
}
// the input is fine
return nil
}
func IsExistingFile(val interface{}) error {
if str, ok := val.(string); ok {
info, err := os.Stat(str)
if os.IsNotExist(err) {
return fmt.Errorf("\"%s\" is not a valid file path", str)
}
if info.IsDir() {
return fmt.Errorf("\"%s\" is a directory, the path must be a file", str)
}
} else {
return fmt.Errorf("cannot check value on response of type %v", reflect.TypeOf(val).Name())
}
// path is real file
return nil
}