1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace Wei\Validator;
10:
11: 12: 13: 14: 15:
16: class IdCardCn extends BaseValidator
17: {
18: protected $invalidMessage = '%name% must be valid Chinese identity card';
19:
20: protected $negativeMessage = '%name% must not be valid Chinese identity card';
21:
22: 23: 24:
25: protected function doValidate($input)
26: {
27: if (!$this->isString($input)) {
28: $this->addError('notString');
29: return false;
30: }
31:
32: $len = strlen($input);
33: if ($len != 15 && $len != 18) {
34: $this->addError('invalid');
35: return false;
36: }
37:
38:
39: if ($len == 15) {
40: $input = substr($input, 0, 6) . '19' . substr($input, 6);
41: }
42:
43:
44: if (!preg_match('/^([0-9]+)$/', substr($input, 0, -1))) {
45: $this->addError('invalid');
46: return false;
47: }
48:
49:
50: $month = substr($input, 10, 2);
51: $day = substr($input, 12, 2);
52: $year = substr($input, 6, 4);
53: if (!checkdate($month, $day, $year)) {
54: $this->addError('invalid');
55: return false;
56: }
57:
58:
59: if (isset($input[17])) {
60: $checksum = $this->calcChecksum($input);
61: if (strtoupper($input[17]) !== $checksum) {
62: $this->addError('invalid');
63: return false;
64: }
65: }
66:
67: return true;
68: }
69:
70: 71: 72: 73: 74: 75:
76: public function calcChecksum($input)
77: {
78: $wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
79: $sum = 0;
80:
81: for ($i = 16; $i >= 0; $i--) {
82: $sum += $input[$i] * $wi[$i];
83: }
84:
85: $checksum = (12 - $sum % 11) % 11;
86:
87: return $checksum == 10 ? 'X' : (string)$checksum;
88: }
89: }
90: