大陆和香港手机号正则校验

大陆和香港手机号正则校验

在日常的开发中,经常会遇到需要校验手机号的情况,这里列举大陆和香港的手机校验。

大陆手机号匹配校验

 /**
     * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数
     * 此方法中前三位格式有:
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4,这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

香港手机号匹配校验

/**
     * 香港手机号码8位数,5|6|8|9开头+7位任意数
     */
    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字,其中 \ 要转义,所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

同时校验大陆和香港号码

/**
     * 大陆号码或香港号码均可
     */
    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }

使用
在app的注册功能中,我们想实现对注册的手机号进行校验,没有通过的手机号不可注册。

if(checkUser(userNameText.getText().toString())){
                     registerErrorText.setText(R.string.used_username);
                     registerErrorText.setVisibility(View.VISIBLE);
                     Log.d(TAG,"该用户名已经被注册");
                 }else{
                     if(!PhoneFormatCheckUtils.isPhoneLegal(userNameText.getText().toString())){
                         registerErrorText.setText(R.string.standardtel);
                         registerErrorText.setVisibility(View.VISIBLE);
                         Log.d(TAG,"手机号码不正确");
                     }else{
                         registerErrorText.setVisibility(View.INVISIBLE);
                         RegisterButton.setEnabled(true);
                         RegisterButton.setClickable(true);
                     }
                 }

效果
在这里插入图片描述
输入手机号短
在这里插入图片描述

输入正确的手机号码即可注册。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值