[英]validate phone number android
我試圖弄清楚我的 android 的驗證電話號碼是如何工作的。
我已經添加了代碼並希望驗證 46123456789,但最后一個數字 (9) 並沒有添加到電話號碼中。
我用這個:
/**
* @param phone
* @return The number which satisfies the above criteria, is a valid mobile Number.
* The first digit should contain number between 0 to 9.
* The rest 9 digit can contain any number between 0 to 9.
* The mobile number can have 11 digits also by including 0 at the starting.
* The mobile number can be of 12 digits also by including 46 at the starting
*/
public static boolean isValidPhoneNumber(String phone) {
phone = trimPhoneNumber(phone);
// The given argument to compile() method
// is regular expression. With the help of
// regular expression we can validate mobile
// number.
// 1) Begins with 0 or 46
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
Pattern p = Pattern.compile("(0/46)?[0-9][0-10]{9}");
// Pattern class contains matcher() method
// to find matching between given number
// and regular expression
Matcher m = p.matcher(phone);
return (m.find() && m.group().equals(phone));
}
public static String trimPhoneNumber(String phone) {
if (TextUtils.isEmpty(phone)) {
return phone;
} else {
try {
phone = phone.replace("+46", "");
phone = phone.replaceAll("[^0-9]", "");//replace all except 0-9
return phone;
} catch (Exception e) {
e.printStackTrace();
return phone;
}
}
}
我錯過了什么嗎
使用這種模式:
^\s*(?:(?:\+?46)|0)(?:\d){9,10}\s*$
^
at start 和$
at end 確保模式匹配整個輸入
\s*
修剪任何空格或制表符\d
捕獲任何數字
(?:\d){9,10}
表示模式(?:\d)
應重復 9 到 10 次。
`` 模式以( +46
或46
)或0
開頭,后跟 9 或 10 位數字。
如果它可以包含-
或數字之間的空格,請使用:
^\s*(?:(?:\+?46)|0)(?:[- ]*\d){9,10}\s*$
你可以在這里測試正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.