0

I am getting phone number input from user as +XXX-X-XXX-XXXX that (+XXX as country code), (X as city Code), (XXX as 1st 3 digits) and , (XXX as 2nd 4 digits). I used regular expression to confirm the entry as in following code;

function validate(form) {
    var phone = form.phone.value;
    var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
    //Checking 'phone' and its regular expressions  
    if(phone == "") {
      inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
    return false;
    }
    if(!phone.match(phoneRegex)) {
      inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
    return false;
    }
  return true;
}

Its working very fine but the problem is that

EDIT : If the user inputs as +XXXXXXXXXXX (all together) and hit enter or go to another field, the input it self set according to the Regex that is +XXX-X-XXX-XXXX.

Can some one guide me with some example how to do this task. Thank you

Community
  • 1
  • 1
AbdulAziz
  • 5,868
  • 14
  • 56
  • 77
  • I vaguely remember a jQuery plugin that does exactly that. Can't remember name though, try searching. EDIT: found it: http://digitalbush.com/projects/masked-input-plugin/ – Madara's Ghost Apr 21 '12 at 07:31
  • possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) (if you don't feel this is the case, you should clarify what you mean by "I want that the user inputs as +XXXXXXXXXXX (all together) and then onblur(), the input it self set it according to the Regex"; unfortunately we are having trouble understanding the grammar.) – ninjagecko Apr 21 '12 at 07:32
  • @ninjagecko: It's not a duplicate of that question. Please read the question before finding duplicates. – Madara's Ghost Apr 21 '12 at 07:33
  • @Truth: the question is incomprehensible. I do not wish to downvote or vote to close as unclear in case the OP or someone clarifies soon. If you disagree and can understand the question, please edit it to be clearer. – ninjagecko Apr 21 '12 at 07:35
  • @Truth this is exactly what I need, but unfortunately I am new to JQuery. Don't know exactly how. Do you have alternative? – AbdulAziz Apr 21 '12 at 07:53
  • @ninjagecko Check the edited question. Sorry for the grammer – AbdulAziz Apr 21 '12 at 07:54
  • @AbdulAziz: no problem, though "the input it self set the input it" is still improper grammar and I still cannot understand; do you mean that upon the element losing focus, if the contents of the input field matches the pattern "+ABCDEFGHIJK" exactly, then the contents of the input field will automatically adjust their formatting, transforming into "+ABC-D-EFG-HIJK"? – ninjagecko Apr 21 '12 at 08:32
  • @ninjagecko Yes brother. You understand me well. Sorry again for the grammar as English is not my native language. – AbdulAziz Apr 21 '12 at 08:59

2 Answers2

1

Try shaping the input:
result = subject.replace(/^((\+|00)\d{2,3})-?(\d{1,2})-?(\d{3})-?(\d{4})$/mg, "$1-$3-$4-$5");

Then do next procedure.

Cylian
  • 10,970
  • 4
  • 42
  • 55
  • As per my understanding, you have to shape-up the inputString(i.e., ``subject``) according to ``+XXX-XX-XXX-XXXX``, by replacing ``subject`` according to ``result``, you get your string in a proper structure. And then check the data. – Cylian Apr 21 '12 at 08:28
  • Do you mean that I don't have to use JQuery now? what do you mean by "And then check the data"? – AbdulAziz Apr 21 '12 at 08:35
1

Set the element's onblur method a callback as follows:

var isValidPhoneNumber = function(string) {
    ...
}

var reformat = function(string) {
    /*
     *  > reformat('example 123 1 1 2 3 123-45')
     *  "+123-1-123-1234"
     */
    var numbers = string.match(/\d/g);
    return '+' + [
        numbers.slice(0,3).join(''),
        numbers.slice(3,4).join(''),
        numbers.slice(4,7).join(''),
        numbers.slice(7,11).join('')
    ].join('-');
}

var reformatPhoneNumber = function() {
    var inputElement = this;
    var value = inputElement.value;

    if (isValidPhoneNumber(value))
        inputElement.value = reformat(inputElement.value);
    else
        // complain to user
}

Here are two example ways you could set the onblur callback handler:

document.getElementById('yourinputelement').onblur = reformatPhoneNumber;
<input ... onblur="reformatPhoneNumber"/>

You can augment reformatPhoneNumber with more validation code if you'd like, or just constantly validate the number as the user is typing it.

To only do this if your phone number is of the form +ABCDEFGHIJK, then add an string.match(/^\+\d{11}$/)!==null to your if statement. (^,$ mean the start and end of the string, \+ means a plus sign, and \d means a digit 0-9, repeated exactly {11} times). Specifically:

function isPlusAndEleventDigits(string) {
    /*
     *  Returns whether string is exactly of the form '+00000000000'
     *  where 0 means any digit 0-9
     */
    return string.match(/^\+\d{11}$/)!==null
}
ninjagecko
  • 88,546
  • 24
  • 137
  • 145