一、手机号格式
1、中国手机号一般为11位数,以1开头,第二位表示号码类型,0-2表示移动,3-5表示联通,6-9表示电信。
2、我们可以使用正则表达式来验证手机号是否符合格式,例如:
function checkPhone(phone) {
let regx = /^1[0-9]{10}$/;
return regx.test(phone);
}
其中,/^1[0-9]{10}$/ 表示以1开头,后面有十个数字,共计11位。
二、手机号归属地
1、我们可以通过手机号前七位来查询手机号的归属地,常用的API有百度API和聚合数据API。
2、以聚合数据API为例,我们可以发送GET请求,获取到对应的归属地信息。
function checkPhoneLocation(phone) {
let url = 'http://apis.juhe.cn/mobile/get?phone=' + phone + '&key=appkey';
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
console.log(data.result);
}
}
}
其中,我们需要先在聚合数据官网申请appkey。
三、手机号运营商
1、我们可以通过手机号前三位来判断手机号的运营商,常用的API有淘宝API和识别号码网站等。
2、以淘宝API为例,我们可以发送GET请求,获取到对应的运营商信息。
function checkPhoneCarrier(phone) {
let url = 'https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=' + phone;
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
let result = xhr.responseText.substring(18, xhr.responseText.length - 1);
let data = JSON.parse(result);
console.log(data.carrier);
}
}
}
其中,我们需要使用字符串截取将json格式的数据提取出来。
四、手机号是否存在
1、我们可以通过发送短信或拨打电话的方式来检查手机号是否存在,以此来进行手机号的验证。
2、以发送短信为例,我们可以调用第三方短信服务商API,发送验证短信。
function sendVerificationCode(phone) {
let url = 'http://yunpian.com/v1/sms/send.json';
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('apikey=apikey&text=您的验证码为1234,请注意查收!&mobile=' + phone);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
console.log(data);
}
}
}
其中,我们需要先在云片网站申请apikey。
五、手机号卡号状态
1、我们可以通过手机号后四位或运营商查询对应的手机号卡号状态,如已停机、欠费等。
2、以运营商查询为例,我们可以发送GET请求,获取到对应的卡号状态信息。
function checkPhoneState(phone) {
let url = 'https://https://www.10010.com/net5/CheckNeedCode.aspx?code=' + phone.substring(7) + '&rd=' + Math.random();
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
let state = xhr.responseText.indexOf('exist') > -1 ? '正常使用' : '已停机或欠费';
console.log(state);
}
}
}
其中,我们需要根据具体运营商的查询方式进行不同的操作。
