Search code examples
javascriptregexphone-numberonblur

Extract substring out of a user input phone number using Javascript


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


Solution

  • 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
    }