Skip to content

Commit 143b21e

Browse files
joeybloggsjoeybloggs
authored andcommitted
Add mac validator
1 parent bd16331 commit 143b21e

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

baked_in.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,12 @@ var BakedInValidators = map[string]Func{
6868
"ipv4": isIPv4,
6969
"ipv6": isIPv6,
7070
"ip": isIP,
71+
"mac": isMac,
72+
}
73+
74+
func isMac(topStruct reflect.Value, currentStruct reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
75+
_, err := net.ParseMAC(field.String())
76+
return err == nil
7177
}
7278

7379
func isIPv4(topStruct reflect.Value, currentStruct reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {

doc.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,12 @@ Here is a list of the current built in validators:
384384
This validates that a string value contains a valid v6 IP Adress.
385385
(Usage: ipv6)
386386
387+
mac
388+
This validates that a string value contains a valid MAC Adress defined
389+
by go's ParseMAC accepted formats and types see:
390+
http://golang.org/src/net/mac.go?s=866:918#L29
391+
(Usage: mac)
392+
387393
Validator notes:
388394
389395
regex

validator_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,41 @@ func AssertError(t *testing.T, errs ValidationErrors, key, field, expectedTag st
119119
EqualSkip(t, 2, val.Tag, expectedTag)
120120
}
121121

122+
func TestMACValidation(t *testing.T) {
123+
tests := []struct {
124+
param string
125+
expected bool
126+
}{
127+
{"3D:F2:C9:A6:B3:4F", true},
128+
{"3D-F2-C9-A6-B3:4F", false},
129+
{"123", false},
130+
{"", false},
131+
{"abacaba", false},
132+
{"00:25:96:FF:FE:12:34:56", true},
133+
{"0025:96FF:FE12:3456", false},
134+
}
135+
136+
for i, test := range tests {
137+
138+
errs := validate.Field(test.param, "mac")
139+
140+
if test.expected == true {
141+
if !IsEqual(errs, nil) {
142+
t.Fatalf("Index: %d mac failed Error: %s", i, errs)
143+
}
144+
} else {
145+
if IsEqual(errs, nil) {
146+
t.Fatalf("Index: %d mac failed Error: %s", i, errs)
147+
} else {
148+
val := errs[""]
149+
if val.Tag != "mac" {
150+
t.Fatalf("Index: %d mac failed Error: %s", i, errs)
151+
}
152+
}
153+
}
154+
}
155+
}
156+
122157
func TestIPValidation(t *testing.T) {
123158
tests := []struct {
124159
param string

0 commit comments

Comments
 (0)