util-go/validate.go
2021-11-25 21:50:12 +08:00

73 lines
1.6 KiB
Go

package util
import (
"errors"
"regexp"
"strings"
"time"
)
//检查手机号
func CheckPhone(phone string) bool {
matched, _ := regexp.MatchString(`^1[3-9]\d{9}$`, phone)
return matched
}
//检查身份证号码
func CheckIdCard(idCard string) bool {
idCard = strings.ToUpper(idCard)
matched, _ := regexp.MatchString(`^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$`, idCard)
if !matched{
return false
}
//校验位
arr := strings.Split(idCard,"")
a := arr[17]
b := GetIdCardSuffix(idCard)
//出生日期
_,err:=GetBirthdayByIdCard(idCard)
if err!=nil{
return false
}
return a==b
}
//计算身份证校验位
func GetIdCardSuffix(idCard string) string {
arr := strings.Split(idCard,"")
weights := []int{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2}
arr2 := []string{"1","0","X","9","8","7","6","5","4","3","2"}
total := 0
for index,weight := range weights{
total += weight * StringToInt(arr[index])
}
offset := total % 11
return arr2[offset]
}
//获取出数日期通过身份证号码
func GetBirthdayByIdCard(idCard string) (time.Time,error){
if len(idCard)<14{
return time.Time{},errors.New("idCard is too short")
}
return time.Parse("20060102",idCard[6:14])
}
//是否为联通号码
func CheckUnicomPhone(phone string) bool {
if !CheckPhone(phone){
return false
}
allows := []string{
"130","131","132","155","156","185","186","145","146",
"166","167",
"175","176","1704","1707","1708","1709","1710","1711","1712","1713","1714","1715","1716","1717","1718","1719",
}
for _,allow := range allows{
if allow==phone[0:len(allow)]{
return true
}
}
return false
}