This repository has been archived by the owner on Sep 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
name.go
64 lines (54 loc) · 1.89 KB
/
name.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
package api
import (
"encoding/json"
"strings"
)
// Name is a basic input.
type Name struct {
ID int `json:"-"`
First string `json:"first"`
FirstInitialOnly bool `json:"firstInitialOnly"`
Middle string `json:"middle"`
MiddleInitialOnly bool `json:"middleInitialOnly"`
NoMiddleName bool `json:"noMiddleName"`
Last string `json:"last"`
Suffix string `json:"suffix"`
SuffixOther string `json:"suffixOther"`
}
// Unmarshal bytes in to the entity properties.
func (entity *Name) Unmarshal(raw []byte) error {
return json.Unmarshal(raw, entity)
}
// Marshal to payload structure
func (entity *Name) Marshal() Payload {
return MarshalPayloadEntity("name", entity)
}
// Valid checks the value(s) against an battery of tests.
func (entity *Name) Valid() (bool, error) {
var stack ErrorStack
first := strings.TrimSpace(entity.First)
if first == "" {
stack.Append("First", ErrFieldRequired{"First name is required"})
} else if entity.FirstInitialOnly && len(first) > 1 {
stack.Append("First", ErrFieldInvalid{"First name should be an initial only"})
}
middle := strings.TrimSpace(entity.Middle)
if entity.NoMiddleName && middle != "" {
stack.Append("Middle", ErrFieldInvalid{"Middle name has a value when it should not"})
} else if middle == "" {
stack.Append("Middle", ErrFieldRequired{"Middle name is required"})
} else if entity.MiddleInitialOnly && len(middle) > 1 {
stack.Append("Middle", ErrFieldInvalid{"Middle name should be an initial only"})
}
last := strings.TrimSpace(entity.Last)
if last == "" {
stack.Append("Last", ErrFieldRequired{"Last name is required"})
}
suffix := strings.TrimSpace(entity.Suffix)
if suffix != "" {
if suffix == "Other" && strings.TrimSpace(entity.SuffixOther) == "" {
stack.Append("Suffix", ErrFieldRequired{"Suffix is required"})
}
}
return !stack.HasErrors(), stack
}