Java驗證手機號


在實際開發中我們需要對手機號格式校驗,以下是對中國手機號校驗的實現。

public class PhoneUtils {

	/**
	 * 中國手機號碼
	 */
	private static Pattern CHINESE_PHONE_PATTERN = Pattern.compile("((13|15|17|18)\\d{9})|(14[57]\\d{8})");

	
	/**
	 * 是否是有效的中國手機號碼
	 * @param phone
	 * @return
	 */
	public static boolean isValidChinesePhone(String phone) {
		if (phone == null || phone.length() != 11) {
			return false;
		}
		
		Matcher matcher = CHINESE_PHONE_PATTERN.matcher(phone);
		return matcher.matches();
	}
	
	
	/**
	 * 檢查手機是否無效
	 * @param phone
	 * @return
	 */
	public static boolean isNotValidChinesePhone(String phone) {
		return !isValidChinesePhone(phone);
	}
	
	
	/**
	 * 手機中間添加星號
	 * @param phone
	 * @param beginIndex
	 * @param endIndex
	 * @return empty string if phone length is illegal
	 */
	public static String setAsterisk(String phone, int beginIndex, int endIndex) {
		
		if (StringUtils.isBlank(phone)) {
			return StringUtils.EMPTY;
		}
		
		if (beginIndex < 0 || endIndex < 0 || beginIndex > phone.length() || endIndex > phone.length()) {
			throw new IllegalArgumentException("illegal index " + beginIndex + "," + endIndex);
		}
		
        StringBuilder phoneWithAsterisk = new StringBuilder(phone.substring(0, beginIndex));  
        
        for (int i = beginIndex; i < endIndex; i++) {  
        	phoneWithAsterisk.append("*");  
        }  
        
        phoneWithAsterisk.append(phone.substring(endIndex, phone.length()));
		return phoneWithAsterisk.toString();
	}
	
	/**
	 * 手機中間添加星號
	 * @param phone
	 * @return
	 */
	public static String setAsterisk(String phone) {
		return setAsterisk(phone, 3, 7);
	}

	/**
	 * 手機中間添加星號,中間六位
	 * @param phone
	 * @return
	 */
	public static String setAsterisk2(String phone) {
		return setAsterisk(phone, 3, 9);
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM