简体   繁体   English

java.util.regex验证电话号码

[英]java.util.regex Validating Phone numbers

I am trying to validate a phone number input from a user(in my project). 我正在尝试验证用户输入的电话号码(在我的项目中)。 This is the method I created trying to validate it and also give them 3 tries to enter a valid format. 这是我创建的试图对其进行验证的方法,并且还给了他们3种尝试输入有效格式的方法。 However what ever I cannot get it to return the prompt that tells them to re enter the number it just runs it true or false. 但是,我无法获得返回提示的提示,告诉他们重新输入数字,它只会运行true或false。 Where am I going wrong. 我要去哪里错了。

public static boolean getPhoneInput(String phone) {
int count =0;
String input,
inputString = phone;          
input = JOptionPane.showInputDialog( phone );
String pattern="(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";               
Pattern p = Pattern.compile(pattern);       
Matcher m = p.matcher(inputString);  
     while ((phone != null && input.length() == 0) && (count <2)){
         input = JOptionPane.showInputDialog("No input was detected \n" + phone);
         count++;}

     if (count==2){
            JOptionPane.showMessageDialog(null, " Sorry due to errors your order cannot be processed.  GOODBYE.");
            System.exit(0);      {           

      }
    }
    return false;} 

I tried to use an example I found and modify it for my program. 我尝试使用发现的示例并对其进行修改。 I am unsure how to get the Boolean type to return a message if they leave the field blank or in an invalid format. 如果它们将字段保留为空白或格式无效,我不确定如何获取布尔类型以返回消息。

I was able to get everything working like a charm within my code using the getPhoneInput() method, however is there a way to return something other than a true or false with a Boolean. 我可以使用getPhoneInput()方法使代码中的所有内容都像魅力一样正常工作,但是有一种方法可以返回布尔值true或false以外的值。 I understand that is what it was built to do, but once I have the correct format i want the number written to a txt file. 我知道这就是它的作用,但是一旦我使用了正确的格式,我就希望将数字写入txt文件。 as it works now instead of logging a number with the users name it just tells me that their phone number matched the required format or that it did not with a true or false. 由于它现在可以正常工作,而不是用用户名记录电话号码,它只是告诉我他们的电话号码与要求的格式匹配,或者电话号码不是真或假。

I've not thoroughly tested this, but it should work for you: 我尚未对此进行全面测试,但它应该对您有用:

public static boolean getPhoneInput(String displayText)
{
    int count = 0;
    String input;
    input = JOptionPane.showInputDialog(displayText);
    String pattern = "\\d-(\\d{3})-(\\d{3})-(\\d{4})";
    Pattern p = Pattern.compile(pattern);
    while ((displayText != null && input.length() == 0))
    {
        input = JOptionPane.showInputDialog("No input was detected \n" + displayText);
        count++;
        if (count == 2)
        {
            JOptionPane.showMessageDialog(null, " Sorry due to errors your order cannot be processed.  GOODBYE.");
            System.exit(0);
        }
    }
    count = 0;
    while (count <= 3)
    {
        count++;
        Matcher m = p.matcher(input);
        if (m.matches())
            return true;
        else
            input = JOptionPane.showInputDialog("Input in wrong format. \n" + displayText);
    }
    return false;
}

Changes Made: 所做的更改:

  1. Moved if statement to inside the while loop, changed while condition, as if statement will already cause the loop to exit if count is 2. if语句移到while循环内,更改while条件,就好像count等于2 if语句已经导致循环退出。
  2. Changed your regex (moved dashes outside of parens, got rid of ? ) 更改了正则表达式(括号内的破折号已移出,摆脱了?
  3. Added an actual check to see if the string matched the pattern. 添加了实际检查,以查看字符串是否与模式匹配。
  4. Moved Matcher m = p.matcher(input); 移动的Matcher m = p.matcher(input); to end of method, otherwise an initial empty input will always return false . 到方法的结尾,否则初始的空输入将始终返回false
  5. inputString was superfluous. inputString是多余的。
  6. You had an extra set of braces following the if that served no discernible purpose. if没有明显目的, if您还有另外一组括号。
  7. Added extra validation step. 添加了额外的验证步骤。

I'd also like to point out that you should probably not use this regex for any real world applications, as it only validates one, very specific, form of phone number. 我还要指出,您可能不应该在任何实际应用中使用此正则表达式,因为它仅验证一种非常具体的电话号码形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM