문제

I have a function which validates the phone number entered by the user using regexp. However it does not seem to evaluate true even though the regexp is correct. I am not sure what i am doing incorrectly.

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

This will work:

  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 «$»

다른 팁

You need to double escape \d inside RegExp constructor, so use this:

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

Or else use regex literal:

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

Since RegExp takes a string as an argument you need to double escape all the special meta characters as one escape is used for String and second is for regex engine.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top