本文收集了一些常用的验证方法,如手机号码验证、银行卡验证等,以后会不定期的更新

1、手机号码验证

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 判断手机格式是否正确
* 表示以1开头,第二位可能是3/4/5/7/8等的任意一个,在加上后面的\d表示数字[0-9]的9位,总共加起来11位结束
*
* @return true 是手机号码
*/
public static boolean isMobile(String mobiles)
{
Pattern p = Pattern.compile("^1[3|4|5|7|8]\\d{9}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}

2、中文验证

1
2
3
4
5
6
7
8
9
10
/**
* 检查是否全部是中文
* @return true 全是中文
*/
public static boolean isChinaise(String body)
{
Pattern p = Pattern.compile("^[\\u4e00-\\u9fa5]+");
Matcher m = p.matcher(body);
return m.matches();
}

3、银行卡校验

Luhn
检验数字算法(Luhn Check Digit Algorithm),也叫做模数10公式,是一种简单的算法,用于验证银行卡、信用卡号码的有效性的算法。对所有大型信用卡公司发行的信用卡都起作用,这些公司包括美国Express、护照、万事达卡、Discover和用餐者俱乐部等。这种算法最初是在20世纪60年代由一组数学家制定,现在Luhn检验数字算法属于大众,任何人都可以使用它。

算法:将每个奇数加倍和使它变为单个的数字,如果必要的话通过减去9和在每个偶数上加上这些值。如果此卡要有效,那么,结果必须是10的倍数。

该校验的过程:
1、从卡号最后一位数字开始,逆向将奇数位(1、3、5等等)相加。
2、从卡号最后一位数字开始,逆向将偶数位数字,先乘以2(如果乘积为两位数,则将其减去9),再求和。
3、将奇数位总和加上偶数位总和,结果应该可以被10整除。

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
/**
* 校验银行卡卡号
*
* @param cardId
* @return
*/
public static boolean isBankCard(String cardId)
{
char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
if (bit == 'N') {
return false;
}
return cardId.charAt(cardId.length() - 1) == bit;
}
/**
* 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
*
* @param nonCheckCodeCardId
* @return
*/
public static char getBankCardCheckCode(String nonCheckCodeCardId)
{
if (nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
|| !nonCheckCodeCardId.matches("\\d+")) {
//如果传的不是数据返回N
return 'N';
}
char[] chs = nonCheckCodeCardId.trim().toCharArray();
int luhmSum = 0;
for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
int k = chs[i] - '0';
if (j % 2 == 0) {
k *= 2;
k = k / 10 + k % 10;
}
luhmSum += k;
}
return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
}

本文地址: http://itdais.com/2016/07/06/通用验证工具类/