github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/validate/validatetpl/hostname.go (about)

     1  package validatetpl
     2  
     3  import "regexp"
     4  
     5  const (
     6  	InvalidHostnameType  = "Hostname 类型错误"
     7  	InvalidHostnameValue = "Hostname 类型值错误"
     8  )
     9  
    10  func init() {
    11  	AddValidateFunc("@hostname", ValidateHostname)
    12  }
    13  
    14  var (
    15  	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])$`)
    16  	reIpAddressLike = regexp.MustCompile(`^(\d+)\.(\d+)\.(\d+)\.(\d+)$`)
    17  )
    18  
    19  func ValidateHostname(v interface{}) (bool, string) {
    20  	s, ok := v.(string)
    21  	if !ok {
    22  		return false, InvalidHostnameType
    23  	}
    24  	if !reHostname.MatchString(s) {
    25  		return false, InvalidHostnameValue
    26  	}
    27  	if reIpAddressLike.MatchString(s) {
    28  		if !reIpAddress.MatchString(s) {
    29  			return false, InvalidHostnameValue
    30  		}
    31  	}
    32  	return true, ""
    33  }