使用RegEx验证电话号码不起作用

时间:2014-05-07 19:01:14

标签: javascript regex validation dojo

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

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());

        }

    } 

2 个答案:

答案 0 :(得分:5)

你需要在\d构造函数中双重转义RegExp,所以使用它:

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

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

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

由于RegExp将字符串作为参数,因此需要对所有特殊元字符进行双重转义,因为一个转义用于String,第二个转义用于正则表达式引擎。

答案 1 :(得分: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());

        }

    } 

REGEX EXPLANATION

/^\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 «$»