forked from go-goyave/goyave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.go
52 lines (44 loc) · 1.53 KB
/
extension.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 validation
import (
"strings"
"github.com/samber/lo"
"goyave.dev/goyave/v5/util/fsutil"
)
// ExtensionValidator validates the field under validation must be a file whose
// filename has one of the specified extensions as suffix.
// Multi-files are supported (all files must satisfy the criteria).
type ExtensionValidator struct {
BaseValidator
Extensions []string
}
// Validate checks the field under validation satisfies this validator's criteria.
func (v *ExtensionValidator) Validate(ctx *Context) bool {
files, ok := ctx.Value.([]fsutil.File)
if !ok {
return false
}
for _, file := range files {
i := strings.Index(file.Header.Filename, ".")
if i == -1 || !lo.ContainsBy(v.Extensions, func(ext string) bool { return strings.HasSuffix(file.Header.Filename[i:], "."+ext) }) {
return false
}
}
return true
}
// Name returns the string name of the validator.
func (v *ExtensionValidator) Name() string { return "extension" }
// MessagePlaceholders returns the ":values" placeholder.
func (v *ExtensionValidator) MessagePlaceholders(_ *Context) []string {
return []string{
":values", strings.Join(v.Extensions, ", "),
}
}
// Extension the field under validation must be a file whose
// filename has one of the specified extensions as suffix.
// Don't include the dot in the extension.
// Composite extensions (e.g. "tar.gz") are supported.
//
// Multi-files are supported (all files must satisfy the criteria).
func Extension(extensions ...string) *ExtensionValidator {
return &ExtensionValidator{Extensions: extensions}
}