-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvalidation.go
63 lines (53 loc) · 1.69 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
package validation
import (
"regexp"
"strings"
"github.com/kennygrant/sanitize"
)
/*
ValidCollectionName ...
Collection names should begin with an underscore or a letter character, and cannot:
- contain the $.
- be an empty string (e.g. "").
- contain the null character.
- begin with the system. prefix. (Reserved for internal use.)
see https://docs.mongodb.com/manual/reference/limits/#Restriction-on-Collection-Names
*/
func ValidCollectionName(name string) bool {
match, err := regexp.MatchString("^[_a-zA-Z][^$\x00]*$", name)
blacklisted, err := regexp.MatchString("^system.*$", strings.ToLower(name))
if err != nil {
return false
}
return match && !blacklisted
}
/*
ValidFieldName ...
- Field names cannot contain the null character.
- Top-level field names cannot start with the dollar sign ($) character.
- Otherwise, starting in MongoDB 3.6, the server permits storage of field names that contain dots (i.e. .) and dollar signs (i.e. $).
- Until support is added in the query language, the use of $ and . in field names is not recommended and is not supported by the official MongoDB drivers.
see https://docs.mongodb.com/manual/reference/limits/#Restriction-on-Field-Names
*/
func ValidFieldName(name string) bool {
match, err := regexp.MatchString("^[^$\x00\\.]+$", name)
if err != nil {
return false
}
return match
}
// MongoSanitize ...
func MongoSanitize(s string) string {
str := sanitize.BaseName(s)
str = strings.ToLower(str)
str = strings.TrimSpace(str)
return strings.Map(func(r rune) rune {
switch r {
case ' ', '\t', '\n', '\r', '$', '.', 0: // Problematic with MongoDB
return '_'
case '/', ':', ';', '|', '-', ',', '#': // Prettier
return '_'
}
return r
}, str)
}