Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -2911,7 +2911,34 @@ func isHostnameRFC952(fl FieldLevel) bool {
}

func isHostnameRFC1123(fl FieldLevel) bool {
return hostnameRegexRFC1123().MatchString(fl.Field().String())
val := fl.Field().String()
if !hostnameRegexRFC1123().MatchString(val) {
return false
}
// RFC 1123 §2.1: "a valid host name can never have the dotted-decimal
// form #.#.#.#, since at least the highest-level component label will
// be alphabetic." If the value has exactly four dot-separated all-numeric
// parts (i.e. it looks like an IPv4 address), accept it only when
// net.ParseIP confirms it is a valid IPv4 address.
if looksLikeIPv4(val) {
return net.ParseIP(val) != nil
}
return true
}

// looksLikeIPv4 reports whether s has exactly four dot-separated parts that
// are each composed entirely of ASCII digits (e.g. "192.168.0.1", "277.168.0.1").
func looksLikeIPv4(s string) bool {
parts := 1
for i := 0; i < len(s); i++ {
c := s[i]
if c == '.' {
parts++
} else if c < '0' || c > '9' {
return false
}
}
return parts == 4
}

func isFQDN(fl FieldLevel) bool {
Expand Down
12 changes: 12 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11078,6 +11078,18 @@ func TestHostnameRFC1123Validation(t *testing.T) {
{"example.", false},
{"test_example", false},
{"192.168.0.1", true},
{"277.168.0.1", false},
{"999.999.999.999", false},
{"0.0.0.0", true},
{"255.255.255.255", true},
{"1.2.3.256", false},
{"3com.com", true},
{"1and1.com", true},
{"7-eleven.com", true},
{"1234", true},
{"12345", true},
{"1.2.3", true},
{"1.2.3.4.5", true},
{"email@example.com", false},
{"2001:cdba:0000:0000:0000:0000:3257:9652", false},
{"2001:cdba:0:0:0:0:3257:9652", false},
Expand Down