File: validators.go

package info (click to toggle)
golang-github-smallstep-cli 0.15.16%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,404 kB
  • sloc: sh: 512; makefile: 99
file content (69 lines) | stat: -rw-r--r-- 1,606 bytes parent folder | download | duplicates (2)
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
61
62
63
64
65
66
67
68
69
package ui

import (
	"fmt"
	"net"
	"strings"

	"github.com/manifoldco/promptui"
)

// NotEmpty is a validation function that checks that the prompted string is not
// empty.
func NotEmpty() promptui.ValidateFunc {
	return func(s string) error {
		if len(strings.TrimSpace(s)) == 0 {
			return fmt.Errorf("value is empty")
		}
		return nil
	}
}

// Address is a validation function that checks that the prompted string is a
// valid TCP address.
func Address() promptui.ValidateFunc {
	return func(s string) error {
		if _, _, err := net.SplitHostPort(s); err != nil {
			return fmt.Errorf("%s is not an TCP address", s)
		}
		return nil
	}
}

// IPAddress is validation function that checks that the prompted string is a
// valid IP address.
func IPAddress() promptui.ValidateFunc {
	return func(s string) error {
		if net.ParseIP(s) == nil {
			return fmt.Errorf("%s is not an ip address", s)
		}
		return nil
	}
}

// DNS is a validation function that changes that the prompted string is a valid
// DNS name.
func DNS() promptui.ValidateFunc {
	return func(s string) error {
		if len(strings.TrimSpace(s)) == 0 {
			return fmt.Errorf("value is empty")
		}
		if _, _, err := net.SplitHostPort(s + ":443"); err != nil {
			return fmt.Errorf("%s is not a valid DNS name", s)
		}
		return nil
	}
}

// YesNo is a validation function that checks for a Yes/No answer.
func YesNo() promptui.ValidateFunc {
	return func(s string) error {
		s = strings.ToLower(strings.TrimSpace(s))
		switch s {
		case "y", "yes", "n", "no":
			return nil
		default:
			return fmt.Errorf("%s is not a valid answer", s)
		}
	}
}