在輸入賬號(hào)時(shí)候,發(fā)送給服務(wù)器前通常需要驗(yàn)證輸入的是不是為空或者格式是不是正確的,從而減少服務(wù)器接受到錯(cuò)誤數(shù)據(jù)
創(chuàng)建一個(gè)RegexUtils類,代碼如下:
public class RegexUtils {
public static boolean isPhoneNumber(final String str) {
Pattern p = null;
Matcher m = null;
boolean b = false;
p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 驗(yàn)證手機(jī)號(hào)
m = p.matcher(str);
b = m.matches();
return b;
}
public static boolean isEmailAddress(final String str){
String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(str);
return matcher.matches();
}
}
在需要驗(yàn)證的地方之間調(diào)用RegexUtils .isPhoneNumber(str)或者RegexUtils .isEmailAddress(str)驗(yàn)證是不是電話號(hào)或者郵箱。歡迎補(bǔ)充其他需要驗(yàn)證的類型。