Add mac validator

pull/128/head
joeybloggs 9 years ago
parent bd16331fc0
commit 143b21eba1
  1. 6
      baked_in.go
  2. 6
      doc.go
  3. 35
      validator_test.go

@ -68,6 +68,12 @@ var BakedInValidators = map[string]Func{
"ipv4": isIPv4, "ipv4": isIPv4,
"ipv6": isIPv6, "ipv6": isIPv6,
"ip": isIP, "ip": isIP,
"mac": isMac,
}
func isMac(topStruct reflect.Value, currentStruct reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
_, err := net.ParseMAC(field.String())
return err == nil
} }
func isIPv4(topStruct reflect.Value, currentStruct reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool { func isIPv4(topStruct reflect.Value, currentStruct reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {

@ -384,6 +384,12 @@ Here is a list of the current built in validators:
This validates that a string value contains a valid v6 IP Adress. This validates that a string value contains a valid v6 IP Adress.
(Usage: ipv6) (Usage: ipv6)
mac
This validates that a string value contains a valid MAC Adress defined
by go's ParseMAC accepted formats and types see:
http://golang.org/src/net/mac.go?s=866:918#L29
(Usage: mac)
Validator notes: Validator notes:
regex regex

@ -119,6 +119,41 @@ func AssertError(t *testing.T, errs ValidationErrors, key, field, expectedTag st
EqualSkip(t, 2, val.Tag, expectedTag) EqualSkip(t, 2, val.Tag, expectedTag)
} }
func TestMACValidation(t *testing.T) {
tests := []struct {
param string
expected bool
}{
{"3D:F2:C9:A6:B3:4F", true},
{"3D-F2-C9-A6-B3:4F", false},
{"123", false},
{"", false},
{"abacaba", false},
{"00:25:96:FF:FE:12:34:56", true},
{"0025:96FF:FE12:3456", false},
}
for i, test := range tests {
errs := validate.Field(test.param, "mac")
if test.expected == true {
if !IsEqual(errs, nil) {
t.Fatalf("Index: %d mac failed Error: %s", i, errs)
}
} else {
if IsEqual(errs, nil) {
t.Fatalf("Index: %d mac failed Error: %s", i, errs)
} else {
val := errs[""]
if val.Tag != "mac" {
t.Fatalf("Index: %d mac failed Error: %s", i, errs)
}
}
}
}
}
func TestIPValidation(t *testing.T) { func TestIPValidation(t *testing.T) {
tests := []struct { tests := []struct {
param string param string

Loading…
Cancel
Save