-
Notifications
You must be signed in to change notification settings - Fork 72
/
validator.go
52 lines (39 loc) · 1.39 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
package contextcmdutil
import (
"regexp"
"github.com/redhat-developer/app-services-cli/pkg/core/errors"
"github.com/redhat-developer/app-services-cli/pkg/core/localize"
"github.com/redhat-developer/app-services-cli/pkg/core/servicecontext"
"github.com/redhat-developer/app-services-cli/pkg/shared/contextutil"
)
// Validator is a type for validating service context inputs
type Validator struct {
Localizer localize.Localizer
SvcContext *servicecontext.Context
}
const (
legalNameChars = "^[a-z]([-a-z0-9]*[a-z0-9])?$"
)
// ValidateName validates the name of the context
func (v *Validator) ValidateName(val interface{}) error {
name, ok := val.(string)
if !ok {
return errors.NewCastError(val, "string")
}
if len(name) < 1 {
return v.Localizer.MustLocalizeError("context.common.validation.name.error.required")
}
matched, _ := regexp.Match(legalNameChars, []byte(name))
if matched {
return nil
}
return v.Localizer.MustLocalizeError("context.common.validation.name.error.invalidChars", localize.NewEntry("Name", name))
}
// ValidateNameIsAvailable validates if the name provided is a unique context name
func (v *Validator) ValidateNameIsAvailable(name string) error {
context, _ := contextutil.GetContext(v.SvcContext, v.Localizer, name)
if context != nil {
return v.Localizer.MustLocalizeError("context.create.log.alreadyExists", localize.NewEntry("Name", name))
}
return nil
}