Created
March 3, 2013 11:35
-
-
Save Centaur/5075737 to your computer and use it in GitHub Desktop.
身份证号验证
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object IDCard { | |
case class IDCard(raw: String) { | |
def verification(data: String) = { | |
val first17 = data.substring(0, 17) | |
val seq = for (ch <- first17; weight <- IDCard.WEIGHT) yield ch.getNumericValue * weight | |
IDCard.VERIFICATION_CODE(seq.sum % 11) | |
} | |
val normalized = raw.length match { | |
case 15 => raw.splitAt(6) match { | |
case (left, right) => | |
val data = left + "19" + right | |
data + verification(data) | |
} | |
case 18 => raw | |
case _ => throw new RuntimeException("无效的身份证号") | |
} | |
val birth = IDCard.dateFormatter.parse(normalized.substring(6, 14)) | |
val valid = birth.before(new java.util.Date()) && birth.after(IDCard.dateFormatter.parse("19000101")) && | |
normalized.matches("""\d{17}\w{1}""") && verification(normalized) == normalized.last | |
val gender = Vector('男, '女)(normalized(17).getNumericValue & 0x01) | |
val isMale = gender == '男 | |
val isFemale = gender == '女 | |
} | |
object IDCard { | |
val WEIGHT = List(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2) | |
val VERIFICATION_CODE = List('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2') | |
val dateFormatter = new java.text.SimpleDateFormat("yyyyMMdd") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment