[英]How to count the number of dashes (-) in a phone number String for input validation?
[英]Input validation phone number
我试图找到一种方法来限制输入电话号码的字段。 示例:应将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开头,不应该包含空格或符号,例如+()等,并且至少应包含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
使用正则表达式匹配/^33\\d{9}$/
要计算某些可能性,您必须分割输入的字符串(在测试“ ..(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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.