代码之家  ›  专栏  ›  技术社区  ›  Martin Labuschin

作为电话号码验证

  •  1
  • Martin Labuschin  · 技术社区  · 15 年前

    我试图验证一个字符串作为电话号码(数字和某些特殊字符)。我使用了一个现有的代码片段: http://snippets.dzone.com/posts/show/597 这似乎是正确的。但每次 string.match(format) 收益率 null ,导致显示错误消息。

    var format = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
    var string = jQuery(".validate_phone").val();
    if (string.match(format) != true) {
      // some error message
    }
    

    我已经查过了, string 填充了预期值。

    以下值应匹配:
    33-4248
    33-42-48
    339 42 42
    339 4248
    3394248个
    (095)3394248
    (095)3394248
    +7(095)3394248
    + 7(095)3394248
    +7(095)3394248
    + 7(095)3394248

    其他所有内容都应该显示错误消息。

    这个代码有什么问题?事先谢谢!

    更新:这里是一个测试用例 http://labuschin.com/material/phone

    3 回复  |  直到 15 年前
        1
  •  3
  •   Martin Labuschin    15 年前

    Facebook上的一位朋友成功帮助我:

    var format = /(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}/;  
    var nr= prompt("Phone number", "");    
    if (nr.match(format) == null) {
      alert ("incorrect");  
    } else {  
      alert ("correct");  
    } 
    

    更改if子句,并删除开头的^和结尾的$。作品在这里: http://labuschin.com/material/phone

        2
  •  0
  •   Max Shawabkeh    15 年前

    有效的regex是: (\+\d\s*)?(\(\s*\d{3}\s*\)\s*)?\d{3}([- ]?\d{2}){2} .

    然而, match() 收益率 null 在非匹配项和匹配项上的捕获值数组上-它将永远不会返回 true . 你可能更感兴趣 search() 如果regex不匹配,则返回匹配位置或-1。例如。:

    var format = /^(\+\d\s*)?(\(\s*\d{3}\s*\)\s*)?\d{3}([- ]?\d{2}){2}$/;
    var string = jQuery(".validate_phone").val();
    if (string.search(format) == -1) {
      // some error message
    }
    
        3
  •  0
  •   Orange    15 年前

    也许吧。。。不应将“string”用作var名称。

    var format = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
    var nr= prompt("Phone number", "");
    if (!nr.match(format)) {
    alert ("incorrect");
    } else {
    alert ("correct");
    } 
    

    为我工作。