简体   繁体   中英

validate phone number android

Im trying to figure out how this validate phone number to my android works.

I have add the code and whant to validate 46123456789 but the last number (9) doesent add to the phone number.

This i use:

/**
     * @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;
            }
        }
    }

Am i missing something

Use this pattern:

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

^ at start and $ at end ensure pattern matches the whole input

\s* trim any space or tab \d capture any digit

(?:\d){9,10} means the pattern (?:\d) should be repeated 9 to 10 times.

`` Pattern start with ( +46 or 46 ) or 0 follow by 9 or 10 digit.

If it could contain - or space between numbers, use this:

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

You could test regex here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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