java校验手机号码、固定电话的合法性

来源:互联网 发布:ubuntu 安装kde桌面 编辑:程序博客网 时间:2024/05/16 18:10

一、规则说明

1、全国固定电话区号大体分两种,三位数和四位数(400固话除外)
中国电话区号三位数有十大城市。分别为:
北京市010
广州市020
上海市021
天津市022
重庆市023
沈阳市024
南京市025
武汉市027
成都市028
西安市029
2、移动电话由于国家的手机号码前三位在不断更新,目前移动、联通、电信三大运营商的手机号段大致如下:
移动号段有134,135,136,137,138,139,147,150,151,152,157,158,159,178,182,183,184,187,188。
联通号段有130,131,132,155,156,185,186,145,176。
电信号段有133,153,177,180,181,189。
中国使用的手机号码为11位,其中各段有不同的编码方向:前3位———网络识别号;第4-7位———地区编码;第8-11位———用户号码

二、工具类

import android.content.Context;import android.text.TextUtils;import android.widget.Toast;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * 类说明:手机号、固定电话合法性校验 */public class PhoneValidatorUtil {    public static boolean matchPhone(String number, int type){        if (TextUtils.isEmpty(number)) {            return false;        }        if (type == 0) {            Matcher m = null;            Pattern p = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的,中间有"-"            //p = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的            m = p.matcher(number);            return m.matches();        } else {            //符合返回true            if (Pattern.matches("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|17[0|6|7|8])\\d{8}$", number)) {                return true;            }        }        return false;    }    /**     *     * @param context     * @param number     * @param type 0 固话 1 手机号     * @return     */    public static boolean matchPhoneShowToast(Context context, String number, int type){        boolean flag = matchPhone(number, type);        if (!flag){            Toast.makeText(context, type == 0 ? "固定电话格式错误" : "移动电话格式错误!",                    Toast.LENGTH_SHORT).show();        }        return flag;    }}

该工具类目前支持13、14、15、17、18开头的号码,基本能支持目前市面上所有的手机号码,后期如有新号段,需再完善,以下为测试用例

//      String number = "0557-5033061";//      String number = "021-62963636";        String number = "029-86261199";        if (PhoneValidatorUtil.matchPhoneShowToast(this, number, 0)){            Log.i("TAG", "固定电话校验成功!");        } else {            Log.i("TAG", "固定电话校验失败!");        }        String phone = "14755296414";        if (PhoneValidatorUtil.matchPhoneShowToast(this, phone, 1)){            Log.i("TAG", "移动电话校验成功!");        } else {            Log.i("TAG", "移动电话校验失败!");        }
原创粉丝点击