我正试图找到一种方法来输入电话号码的字段限制。
例:
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");
}
答案 0 :(得分:1)
“基本上数字永远不应该从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("012345678".matches("[1-9][0-9]{8,}"));//false
答案 1 :(得分:0)
使用正则表达式匹配/^33\d{9}$/
答案 2 :(得分:0)
要计算一些可能性,你必须拆分输入的字符串(在测试“..(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 01234567890
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 012346577979
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());
}