繁体   English   中英

验证电话号码 android

[英]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 次。

`` 模式以( +4646 )或0开头,后跟 9 或 10 位数字。

如果它可以包含-或数字之间的空格,请使用:

^\s*(?:(?:\+?46)|0)(?:[- ]*\d){9,10}\s*$

你可以在这里测试正则表达式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM