-
Notifications
You must be signed in to change notification settings - Fork 0
/
builtin_resident_id.go
87 lines (77 loc) · 2.39 KB
/
builtin_resident_id.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// 版权所有 GoFrame 作者(https://goframe.org)。保留所有权利。
//
// 本源代码形式遵循 MIT 许可协议条款。如果随此文件未分发 MIT 许可副本,
// 您可以在 https://github.com/gogf/gf 获取一份。
package builtin
import (
"errors"
"strconv"
"strings"
"github.com/888go/goframe/text/gregex"
)
// RuleResidentId 实现了 `resident-id` 规则:
// 居民身份证号码。
//
// 格式:居民身份证号
type RuleResidentId struct{}
func init() {
Register(RuleResidentId{})
}
func (r RuleResidentId) Name() string {
return "resident-id"
}
func (r RuleResidentId) Message() string {
return "The {field} value `{value}` is not a valid resident id number"
}
func (r RuleResidentId) Run(in RunInput) error {
if r.checkResidentId(in.Value.String()) {
return nil
}
return errors.New(in.Message)
}
// checkResidentId checks whether given id a china resident id number.
//
// xxxxxx yyyy MM dd 375 0 十八位
// xxxxxx yy MM dd 75 0 十五位
//
// 地区: [1-9]\d{5}
// 年的前两位:(18|19|([23]\d)) 1800-2399
// 年的后两位:\d{2}
// 月份: ((0[1-9])|(10|11|12))
// 天数: (([0-2][1-9])|10|20|30|31) 闰年不能禁止29+
//
// 三位顺序码:\d{3}
// 两位顺序码:\d{2}
// 校验码: [0-9Xx]
//
// 十八位:^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$
// 十五位:^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$
//
// 总:
// (^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)
func (r RuleResidentId) checkResidentId(id string) bool {
id = strings.ToUpper(strings.TrimSpace(id))
if len(id) != 18 {
return false
}
var (
weightFactor = []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
checkCode = []byte{'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'}
last = id[17]
num = 0
)
for i := 0; i < 17; i++ {
tmp, err := strconv.Atoi(string(id[i]))
if err != nil {
return false
}
num = num + tmp*weightFactor[i]
}
if checkCode[num%11] != last {
return false
}
return 正则类.X是否匹配文本(
`(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)`,
id,
)
}