在實際開發中,時常遇到像身份證/郵箱/電話號碼等信息的驗證。本文將結合實際開發中經常遇到的情況給出常見的驗證方法。
身份證
目前所有的互聯網都涉及到實名認證,實名認證中重要的是身份證信息。每個人只有獨一無二的身份確認。
驗證長度
/**
* 身份證驗證
*
* @param id 號碼內容
* @return 是否有效
*/
public static boolean isValid(String id) {
Boolean validResult = true;
//校驗長度只能爲15或18
int len = id.length();
if (len != FIFTEEN_ID_CARD && len != EIGHTEEN_ID_CARD) {
validResult = false;
}
//校驗生日
if (!validDate(id)) {
validResult = false;
}
return validResult;
}
驗證身份證格式
public static String checkIdCard(String idCard) {
String regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}";
if (Pattern.matches(regex, idCard)) {
return idCard;
} else {
throw new CustomException(ResultEnum.IDCARD_LEGAL);
}
}
郵箱
/**
* * 驗證Email
* * @param email email地址,格式:[email protected],[email protected],xxx代表郵件服務商
* * @return 驗證成功返回true,驗證失敗返回false
*
*/
public static boolean checkEmail(String email) {
String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
return Pattern.matches(regex, email);
}
生成自定的UUID
public class UUIDUtil {
final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z'};
final static Map<Character, Integer> digitMap = new HashMap<Character, Integer>();
static {
for (int i = 0; i < digits.length; i++) {
digitMap.put(digits[i], (int) i);
}
}
/**
* 支持的最大進制數
*/
public static final int MAX_RADIX = digits.length;
/**
* 支持的最小進制數
*/
public static final int MIN_RADIX = 2;
/**
* 將長整型數值轉換爲指定的進制數(最大支持62進制,字母數字已經用盡)
*
* @param i
* @param radix
* @return
*/
public static String toString(long i, int radix) {
if (radix < MIN_RADIX || radix > MAX_RADIX) {
radix = 10;
}
if (radix == 10) {
return Long.toString(i);
}
final int size = 65;
int charPos = 64;
char[] buf = new char[size];
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = digits[(int) (-(i % radix))];
i = i / radix;
}
buf[charPos] = digits[(int) (-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (size - charPos));
}
static NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
/**
* 將字符串轉換爲長整型數字
*
* @param s 數字字符串
* @param radix 進制數
* @return
*/
public static long toNumber(String s, int radix) {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < MIN_RADIX) {
throw new NumberFormatException("radix " + radix
+ " less than Numbers.MIN_RADIX");
}
if (radix > MAX_RADIX) {
throw new NumberFormatException("radix " + radix
+ " greater than Numbers.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
Integer digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+') {
throw forInputString(s);
}
if (len == 1) {
throw forInputString(s);
}
i++;
}
multmin = limit / radix;
while (i < len) {
digit = digitMap.get(s.charAt(i++));
if (digit == null) {
throw forInputString(s);
}
if (digit < 0) {
throw forInputString(s);
}
if (result < multmin) {
throw forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw forInputString(s);
}
result -= digit;
}
} else {
throw forInputString(s);
}
return negative ? result : -result;
}
/**
* 編寫uuid生成工具方法
*
* @param val
* @param digits
* @return
*/
public static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return toString(hi | (val & (hi - 1)), MAX_RADIX)
.substring(1);
}
/**
* 以62進制(字母加數字)生成19位UUID,最短的UUID
*
* @return
*/
public static String uuid() {
UUID uuid = UUID.randomUUID();
StringBuilder sb = new StringBuilder();
sb.append(digits(uuid.getMostSignificantBits() >> 32, 8));
sb.append(digits(uuid.getMostSignificantBits() >> 16, 4));
sb.append(digits(uuid.getMostSignificantBits(), 4));
sb.append(digits(uuid.getLeastSignificantBits() >> 48, 4));
sb.append(digits(uuid.getLeastSignificantBits(), 12));
return sb.toString();
}
public static String getUUID(String type) {
return getBasicNo(type) + RandomStringUtils.randomAlphanumeric(20);
}
}
驗證URL
/**
* * 驗證URL地址
* * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80
* * @return 驗證成功返回true,驗證失敗返回false
*
*/
public static boolean checkURL(String url) {
String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?";
return Pattern.matches(regex, url);
}
時間轉換
字符串處理
大小寫轉換
String 類的 toLowerCase() 方法可以將字符串中的所有字符全部轉換成小寫,而非字母的字符不受影響。語法格式如下:
字符串名.toLowerCase() // 將字符串中的字母全部轉換爲小寫,非字母不受影響
toUpperCase() 則將字符串中的所有字符全部轉換成大寫,而非字母的字符不受影響。語法格式如下:
字符串名.toUpperCase() // 將字符串中的字母全部轉換爲大寫,非字母不受影響
截取字符串
substring(int beginIndex) 形式
此方式用於提取從索引位置開始至結尾處的字符串部分。調用時,括號中是需要提取字符串的開始位置,方法的返回值是提取的字符串。例如:
String str = "我愛 Java 編程";
String result = str.substring(3); // 輸出:Java 編程
2. substring(int beginIndex,int endIndex) 形式
此方法中的 beginIndex 表示截取的起始索引,截取的字符串中包括起始索引對應的字符;endIndex 表示結束索引,截取的字符串中不包括結束索引對應的字符,如果不指定 endIndex,則表示截取到目標字符串末尾。該方法用於提取位置 beginIndex 和位置 endIndex 位置之間的字符串部分。
StringBuffer、StringBuilder、String 中都實現了 CharSequence 接口。CharSequence 是一個定義字符串操作的接口,它只包括 length()、charAt(int index)、subSequence(int start, int end) 這幾個 API。
String 是 Java 中基礎且重要的類,被聲明爲 final class,是不可變字符串。因爲它的不可變性,所以拼接字符串時候會產生很多無用的中間對象,如果頻繁的進行這樣的操作對性能有所影響。
StringBuffer 就是爲了解決大量拼接字符串時產生很多中間對象問題而提供的一個類。它提供了 append 和 add 方法,可以將字符串添加到已有序列的末尾或指定位置,它的本質是一個線程安全的可修改的字符序列。
在很多情況下我們的字符串拼接操作不需要線程安全,StringBuilder 登場。
StringBuilder 是 JDK1.5 發佈的,它和 StringBuffer去掉了保證線程安全的那部分,減少了開銷。
線程安全:
StringBuffer:線程安全
StringBuilder:線程不安全
速度:
一般情況下,速度從快到慢爲 StringBuilder > StringBuffer > String,當然這是相對的,不是絕對的。
使用環境:
操作少量的數據使用 String。
單線程操作大量數據使用 StringBuilder。
多線程操作大量數據使用 StringBuffer
隨機數
public class MathUtils {
public static String getRandNum(int min, int max) {
int randNum = min + (int) (Math.random() * ((max - min) + 1));
return ConfigCommens.BLOG_RANDOM + randNum;
}
}
根據身份證獲取出生日期,性別,年齡等
/**
* 15位身份證號
*/
private static final Integer FIFTEEN_ID_CARD = 15;
/**
* 18位身份證號
*/
private static final Integer EIGHTEEN_ID_CARD = 18;
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
/**
* 根據身份證號獲取性別
*
* @param IDCard
* @return
*/
public static String getSex(String IDCard) {
String sex = "";
if (StringUtils.isNotBlank(IDCard)) {
//15位身份證號
if (IDCard.length() == FIFTEEN_ID_CARD) {
if (Integer.parseInt(IDCard.substring(14, 15)) % 2 == 0) {
sex = "F";
} else {
sex = "M";
}
//18位身份證號
} else if (IDCard.length() == EIGHTEEN_ID_CARD) {
// 判斷性別
if (Integer.parseInt(IDCard.substring(16).substring(0, 1)) % 2 == 0) {
sex = "M";
} else {
sex = "F";
}
}
}
return sex;
}
/**
* 根據身份證號獲取年齡
*
* @param IDCard
* @return
*/
public static Integer getAge(String IDCard) {
Integer age = 0;
Date date = new Date();
if (StringUtils.isNotBlank(IDCard) && isValid(IDCard)) {
//15位身份證號
if (IDCard.length() == FIFTEEN_ID_CARD) {
// 身份證上的年份(15位身份證爲1980年前的)
String uyear = "19" + IDCard.substring(6, 8);
// 身份證上的月份
String uyue = IDCard.substring(8, 10);
// 當前年份
String fyear = format.format(date).substring(0, 4);
// 當前月份
String fyue = format.format(date).substring(5, 7);
if (Integer.parseInt(uyue) <= Integer.parseInt(fyue)) {
age = Integer.parseInt(fyear) - Integer.parseInt(uyear) + 1;
// 當前用戶還沒過生
} else {
age = Integer.parseInt(fyear) - Integer.parseInt(uyear);
}
//18位身份證號
} else if (IDCard.length() == EIGHTEEN_ID_CARD) {
// 身份證上的年份
String year = IDCard.substring(6).substring(0, 4);
// 身份證上的月份
String yue = IDCard.substring(10).substring(0, 2);
// 當前年份
String fyear = format.format(date).substring(0, 4);
// 當前月份
String fyue = format.format(date).substring(5, 7);
// 當前月份大於用戶出身的月份表示已過生日
if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) {
age = Integer.parseInt(fyear) - Integer.parseInt(year) + 1;
// 當前用戶還沒過生日
} else {
age = Integer.parseInt(fyear) - Integer.parseInt(year);
}
}
}
return age;
}
/**
* 獲取出生日期 yyyy年MM月dd日
*
* @param IDCard
* @return
*/
public static String getBirthday(String IDCard) {
String birthday = "";
String year = "";
String month = "";
String day = "";
if (StringUtils.isNotBlank(IDCard)) {
//15位身份證號
if (IDCard.length() == FIFTEEN_ID_CARD) {
// 身份證上的年份(15位身份證爲1980年前的)
year = "19" + IDCard.substring(6, 8);
//身份證上的月份
month = IDCard.substring(8, 10);
//身份證上的日期
day = IDCard.substring(10, 12);
//18位身份證號
} else if (IDCard.length() == EIGHTEEN_ID_CARD) {
// 身份證上的年份
year = IDCard.substring(6).substring(0, 4);
// 身份證上的月份
month = IDCard.substring(10).substring(0, 2);
//身份證上的日期
day = IDCard.substring(12).substring(0, 2);
}
birthday = year + "-" + month + "-" + day;
}
return birthday;
}
具體的方法請關注公衆號 【一抹浮雲】,輸入 “驗證”即可