github.com/profzone/eden-framework@v1.0.10/pkg/validate/validatetpl/hostname.go (about) 1 package validatetpl 2 3 import ( 4 "regexp" 5 ) 6 7 const ( 8 InvalidHostnameType = "Hostname 类型错误" 9 InvalidHostnameValue = "Hostname 类型值错误" 10 ) 11 12 func init() { 13 AddValidateFunc("@hostname", ValidateHostname) 14 } 15 16 var ( 17 reHostname = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`) 18 reIpAddressLike = regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)\.(\d+)$`) 19 ) 20 21 func ValidateHostname(v interface{}) (bool, string) { 22 s, ok := v.(string) 23 if !ok { 24 return false, InvalidHostnameType 25 } 26 if !reHostname.MatchString(s) { 27 return false, InvalidHostnameValue 28 } 29 if reIpAddressLike.MatchString(s) { 30 if !reIpAddress.MatchString(s) { 31 return false, InvalidHostnameValue 32 } 33 } 34 return true, "" 35 }