验证 Android 中的手机号码 [英] Validation for a cell number in Android

查看:32
本文介绍了验证 Android 中的手机号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a UI where user enters the cell number and the number is stored in a string variable and then its stored into the database.

I want to validate the string to check whether the string does not contain any characters.

How do I do that?

Below is the string code.

EditText editText3 = (EditText) this.findViewById(R.id.editText2);
setNum = editText3.getText().toString(); //setNum would contain something link 8081124589

解决方案

To validate a string, use

if (setNum.matches(regexStr))

where regexStr can be:

//matches numbers only
String regexStr = "^[0-9]*$"

//matches 10-digit numbers only
String regexStr = "^[0-9]{10}$"

//matches numbers and dashes, any order really.
String regexStr = "^[0-9\-]*$"

//matches 9999999999, 1-999-999-9999 and 999-999-9999
String regexStr = "^(1\-)?[0-9]{3}\-?[0-9]{3}\-?[0-9]{4}$"


There's a very long regex to validate phones in the US (7 to 10 digits, extensions allowed, etc.). The source is from this answer: A comprehensive regex for phone number validation

String regexStr = "^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$"

这篇关于验证 Android 中的手机号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆