2014-05-07 20 views
0

我有一个function,它验证用户使用正则表达式输入的电话号码。然而,即使正则表达式是正确的,它似乎也没有评估true。我不确定我做错了什么。使用RegExp无法验证电话号码

的Html

<body class="claro"> 
    <form id="myform" data-dojo-type="dijit/form/Form"> 

    <input 
    data-dojo-type="dijit/form/ValidationTextBox" 
     data-dojo-props=" 
      required: true, 
      invalidMessage: 'Invalid Phone Number !', 
      missingMessage: 'Phone Number Required !'" 
     id="phone" title="Phone Number" 
    placeholder="Your Phone Number" 
    onkeydown="validatePhoneNumberFormat()"/> 

    </form> 
</body> 

的Javascript

//test phone number 188-123-1234 
    function validatePhoneNumberFormat(){ 
    var phoneNumber = dijit.byId("phone"); 
     var phoneFormat = new RegExp('^[0-9]\d{2}-\d{3}-\d{4}$'); 
     phoneNumber.validator = function(value){ 
      console.log(value); 
      console.log(phoneFormat.test(value.trim())); 
      return phoneFormat.test(value.trim()); 

     } 

    } 
+0

哎呀!不要强制特定的格式。去除所有不重要的字符(所以保留数字和'+'(希望这就是你所需要的)),然后测试真正重要的位。 (我的电话号码是BTW,里面有12位数字,所以你应该重新考虑一下你对电话号码构成的想法) – Quentin

+0

确保你的用例仅限于特定的地理区域和某些数字,因为这种硬编码不适合本地化或可选区域代码。 – indivisible

+0

[HTML5占位符属性不能代替标签元素](http://www.456bereastreet.com/archive/201204/the_html5_placeholder_attribute_is_not_a_substitute_for_the_label_element /) – Quentin

回答

2

这将工作:

function validatePhoneNumberFormat(){ 
    var phoneNumber = dijit.byId("phone"); 
     var phoneFormat = /^\d{3}-\d{3}-\d{4}$/; 
     phoneNumber.validator = function(value){ 
      console.log(value); 
      console.log(phoneFormat.test(value.trim())); 
      return phoneFormat.test(value.trim()); 

     } 

    } 

正则表达式的说明

/^\d{3}-\d{3}-\d{4}$/ 

Assert position at the beginning of the string «^» 
Match a single character that is a “digit” (ASCII 0–9 only) «\d{3}» 
    Exactly 3 times «{3}» 
Match the character “-” literally «-» 
Match a single character that is a “digit” (ASCII 0–9 only) «\d{3}» 
    Exactly 3 times «{3}» 
Match the character “-” literally «-» 
Match a single character that is a “digit” (ASCII 0–9 only) «\d{4}» 
    Exactly 4 times «{4}» 
Assert position at the very end of the string «$» 
5

你需要加倍逃避\dRegExp构造,所以用这个:

var phoneFormat = new RegExp('^\\d{3}-\\d{3}-\\d{4}$'); 

或者使用正则表达式文字:

var phoneFormat = /^\d{3}-\d{3}-\d{4}$/; 

由于RegExp需要一个字符串,你需要加倍逃避所有的特殊元字符作为一个逃生用于字符串和第二个是正则表达式引擎的参数。

+2

使用正则表达式文字比修复构造函数方法更好。 – Quentin

+0

谢谢我用这个选项编辑。 – anubhava

+1

为什么'[0-9] \ d {2}'而不是'\ d {3}'? –