سؤال

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