输入验证电话号码
问题描述:
我想找到一种方法来使输入电话号码的字段限制。 实施例: France (country code 33) local number 0142687984
应该输入作为 33142687984
输入验证电话号码
,而不是例如 00331 42687984, 0033 (1) 42687984, +33 1 42 68 79 84
等
基本上数量不应该从0开始,不应包括空格或标志等+()等,并应具有至少9位数
我一直在试图找到一个洪水脚本样本,但没有成功。请帮助
我有这个至今:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String nom = request.getParameter("nom");
String prenom = request.getParameter("prenom");
String phone = request.getParameter("phone");
String adressefacturation = request.getParameter("adressefacturation");
String ZIPfacturation = request.getParameter("ZIPfacturation");
String paysfacturation = request.getParameter("paysfacturation");
String adresseexpedition = request.getParameter("adresseexpedition");
String ZIPexpedition = request.getParameter("ZIPexpedition");
String paysexpedition = request.getParameter("paysexpedition");
String CardNumber = request.getParameter("CardNumber");
String CardDateOfExpiry = request.getParameter("CardDateOfExpiry");
String password = request.getParameter("password");
}
答
计算一些posibilities你要输入的字符串分割什么(试验后 “(1)..”):
// String[] litteralPhone = request.getParameter("phone").split(" ") ;
final String litteralPhone = "0033 (119999999990";
final int i = litteralPhone.indexOf(")");
if (i > 0) {
if (litteralPhone.substring(i).length() > 8) {
System.out.println(litteralPhone.replaceAll(
"^[0]{1,}|[ ]{0,}\\(|\\)[ ]{0,}", ""));
} else {
System.out.println("error with()");
}
} else {
// suppress trailing (
final String[] tabNum = litteralPhone.replaceAll("\\(|\\)", "").split(" ");
switch (tabNum.length) {
case 1 : // 003311236549879879
tabNum[0] = tabNum[0].replaceAll("^[0]{1,}", "");
if (tabNum[0].length() < 10) { // tune this lenght
System.out.println("error 1");
}
break;
case 2 : // 033
tabNum[0] = tabNum[0].replaceAll("^[0]{1,}", "");
tabNum[1] = tabNum[1].replaceAll("^[0]", "");
if (tabNum[1].length() < 8) {
System.out.println("error 2");
}
break;
case 3 : // +33 1
tabNum[0] = tabNum[0].replaceAll("^[0]{1,}", "");
tabNum[2] = tabNum[2].replaceAll("^[0]", "");
if (tabNum[2].length() < 8) {
System.out.println("error 3");
}
// add all cases here
default :
System.out.println("not a good phone number");
break;
}
final StringBuilder sb = new StringBuilder();
for (final String string : tabNum) {
sb.append(string);
}
System.out.println(sb.toString());
}
答
“基本数不应该从0开始,不应该包含空格或象星座+()等,并应至少有9位数字“,所以我假定你只接受以1-9位开头的数字,然后只能包含其他数字(至少8位数字)。
它这是你想尝试这个表达式[1-9][0-9]{8,}
System.out.println("123456789".matches("[1-9][0-9]{8,}"));//true
System.out.println("12345678".matches("[1-9][0-9]{8,}"));//false
System.out.println("".matches("[1-9][0-9]{8,}"));//false
是否要将验证直接添加到您的bean属性中,或者应该在何处执行检查? – Keppil 2012-07-19 12:54:12