/
validation.go
65 lines (54 loc) · 1.4 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
61
62
63
64
65
package ocdav
import (
"errors"
"fmt"
"strings"
"github.com/cs3org/reva/v2/internal/http/services/owncloud/ocdav/config"
)
// Validator validates strings
type Validator func(string) error
// ValidatorsFromConfig returns the configured Validators
func ValidatorsFromConfig(c *config.Config) []Validator {
// we always want to exclude empty names
vals := []Validator{notEmpty()}
// forbidden characters
vals = append(vals, doesNotContain(c.NameValidation.InvalidChars))
// max length
vals = append(vals, isShorterThan(c.NameValidation.MaxLength))
return vals
}
// ValidateName will validate a file or folder name, returning an error when it is not accepted
func ValidateName(name string, validators []Validator) error {
for _, v := range validators {
if err := v(name); err != nil {
return fmt.Errorf("name validation failed: %w", err)
}
}
return nil
}
func notEmpty() Validator {
return func(s string) error {
if strings.TrimSpace(s) == "" {
return errors.New("must not be empty")
}
return nil
}
}
func doesNotContain(bad []string) Validator {
return func(s string) error {
for _, b := range bad {
if strings.Contains(s, b) {
return fmt.Errorf("must not contain %s", b)
}
}
return nil
}
}
func isShorterThan(maxLength int) Validator {
return func(s string) error {
if len(s) > maxLength {
return fmt.Errorf("must be shorter than %d", maxLength)
}
return nil
}
}