forked from raystack/optimus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
validator.go
58 lines (51 loc) · 1.4 KB
/
validator.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
package utils
import (
"errors"
"fmt"
"reflect"
"regexp"
"github.com/AlecAivazis/survey/v2"
"github.com/robfig/cron/v3"
)
// CronIntervalValidator return a nil value when a valid cron string is passed
// used in gopkg.in/validator.v2
func CronIntervalValidator(val interface{}, _ string) error {
value, ok := val.(string)
if !ok {
return fmt.Errorf("invalid crontab entry, not a valid string")
}
// an empty schedule is a valid schedule
if value == "" {
return nil
}
if _, err := cron.ParseStandard(value); err != nil {
return fmt.Errorf("invalid crontab entry: %w", err)
}
return nil
}
// validatorFactory, name abbreviated so that
// the global implementation can be called 'validatorFactory'
type VFactory struct{}
func (*VFactory) NewFromRegex(re, message string) survey.Validator {
regex := regexp.MustCompile(re)
return func(v interface{}) error {
k := reflect.ValueOf(v).Kind()
if k != reflect.String {
return fmt.Errorf("was expecting a string, got %s", k.String())
}
val, ok := v.(string)
if !ok {
return fmt.Errorf("error to cast [%+v] to string type", v)
}
matched := regex.MatchString(val)
if matched == false {
return errors.New(message)
}
return nil
}
}
var ValidatorFactory = new(VFactory)
// ValidateCronInterval return a nil value when a valid cron string is passed
func ValidateCronInterval(val interface{}) error {
return CronIntervalValidator(val, "")
}