IMEI,手机号,身份证号格式有效性校验
IMEI格式有效性校验手机号格式有效性校验身份证格式有效性校验IMEI格式有效性校验
imei一般由15位数字组成,有些厂家会在最后加上两位数字表示版本号。imei的校验主要通过模10算法,基于前14位的数字校验第15位的数值。
class IsValidIMEI: AbstractScalar(), (String) -> Boolean {//一般的imei基本都是15位,有些17位的,后两位是版本号private val regex : Regex = Regex("\\d{15}|\\d{17}")override operator fun invoke(imei: String): Boolean {if (imei.isEmpty()){return false}return regex.matches(imei) && luhnAlgorithm(imei)}private fun luhnAlgorithm(imei: String): Boolean{var sum1 = 0var sum2 = 0var index = 0while (index < 14){val num = imei[index].toString().toInt()if (index % 2 == 0){sum1 += num} else {val temp = num * 2sum2 += temp / 10 + temp % 10}index ++}var last = (sum1 + sum2) % 10if (last != 0){last = 10 - last}return last == imei[14].toString().toInt()}}
手机号格式有效性校验
手机号如果不算前缀的国家码,一般由11位数字组成。主要校验的就是前三位运营商号码,这个号码资源可以去工信部网站查,时不时会更新
private val regex : Regex = Regex("^((1[3,8][0-9])|(14[5,7,9])|(15[0-3,5-9])|(17[0,3,5-8])|166|192|198|199)\\d{8}$")
身份证格式有效性校验
身份证的格式,网上也有很多了,国内大陆地区都是18位,对最后一位采用模11-2算法校验。
class IsValidIdentityCard: AbstractScalar(), (String) -> Boolean {private val regex18 : Regex = Regex("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")private val regex15 : Regex = Regex("^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$")private val idCardWi = listOf(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2)private val idCardY = listOf("1","0","X","9","8","7","6","5","4","3","2")override operator fun invoke(id: String): Boolean {if (id.isEmpty()){return false}return when {id.length == 18 -> regex18.matches(id) && lastNumberIsValid(id)id.length == 15 -> regex15.matches(id)else -> false}}private fun lastNumberIsValid(id: String): Boolean{val charArray = id.toCharArray()var sum = 0var index = 0while (index < idCardWi.size){val current = charArray[index].toString().toInt()sum += current * idCardWi[index]index += 1}val lastID = charArray[17].toString()val mode = sum % 11return if (idCardY[mode].equals(lastID, true)){true} else {logger.warn("ID $id is invalid, because last number should be ${idCardY[mode]}.")false}}}