Pages

Saturday, July 23, 2016

Coding Challenge: Telephone number check

Oh, I know it's boring and horrible, but let's make a function that verifies the telephone number entered by the user is in a correct format.

Here are the rules for a correct format:

telephoneCheck("555-555-5555") should return true.
telephoneCheck("1 555-555-5555") should return true.
telephoneCheck("1 (555) 555-5555") should return true.
telephoneCheck("5555555555") should return true.
telephoneCheck("555-555-5555") should return true.
telephoneCheck("(555)555-5555") should return true.
telephoneCheck("1(555)555-5555") should return true.
telephoneCheck("555-5555") should return false.
telephoneCheck("5555555") should return false.
telephoneCheck("1 555)555-5555") should return false.
telephoneCheck("1 555 555 5555") should return true.
telephoneCheck("1 456 789 4444") should return true.
telephoneCheck("123**&!!asdf#") should return false.
telephoneCheck("55555555") should return false.
telephoneCheck("(6505552368)") should return false
telephoneCheck("2 (757) 622-7382") should return false.
telephoneCheck("0 (757) 622-7382") should return false.
telephoneCheck("-1 (757) 622-7382") should return false
telephoneCheck("2 757 622-7382") should return false.
telephoneCheck("10 (757) 622-7382") should return false.
telephoneCheck("27576227382") should return false.
telephoneCheck("(275)76227382") should return false.
telephoneCheck("2(757)6227382") should return false.
telephoneCheck("2(757)622-7382") should return false.
telephoneCheck("555)-555-5555") should return false.
telephoneCheck("(555-555-5555") should return false.
telephoneCheck("(555)5(55?)-5555") should return false.


If a country code is used, it must be 1.  

Good luck.  Solution is in the comments.  

1 comment:

  1. function telephoneCheck(str) {
    str = str.replace(/ /g, '');
    var paranCheck;
    var numCount=0;
    var charCheck = /^[0-9-()]+$/;
    str = str.split("");
    str.forEach(function(item){
    if(!Number.isNaN(Number(item))){
    numCount ++;
    }
    });

    str = str.join("");

    if(numCount > 11){
    return false;
    }

    if(numCount > 10 && str[0] !== "1"){
    return false;
    }

    if(numCount < 10){
    return false;
    }


    if(!charCheck.test(str)){
    return false;
    }

    paranCheck = str.match(/[()]/g);

    if(!(paranCheck === null)){

    if(paranCheck.length > 2){
    return false;
    }

    if(paranCheck.length < 2){
    return false;
    }

    if(str[0] === "(" && str[4] === ")"){
    return true;
    }

    if(str[1] === "(" && str[5] === ")"){
    return true;
    }
    else{
    return false;
    }
    }



    return true;
    }

    ReplyDelete