-2

I have a input field for a phonenumber.

Now i want to check with jquery/javascript the syntax and the characters of the number

I only accept this format: 31-123456789 (also more groupes seperated by - will be ok)

Its important to check if there is the international code at first.

I think about to do a kind of replace for replace "()/.:;" characters and check if the first letter is a 0.

But this looks for large code, also there is not check if the user has enter disallowed characters for example Abc...

How i can check and format the following examples in the easiest way?

031(123)123 -> should return 31-123-123
(0123)123 -> should return a error (no international code)
031.123 -> should return a error (no international code)
31.(123)123 -> 31-123-123
+31.123.123 -> 31-123-123
+31 (123) 123 -> 31-123-123

etc.

Thanks for showing and explaing me the way to do it.

guest271314
  • 1
  • 15
  • 104
  • 177
mikeD
  • 229
  • 2
  • 11

1 Answers1

1

Here is a try, that you could build on. It also fill all your requirement.

Now you can simply add your configration to internationalCodes and the method will do its job

   // All valid internationl code
    var internationalCodes= [
    { codes:["031", "0031", "31"], translateTo: "31", minLength: 8 }
    ]
    var seperatorCount =3;
    var seperator = "-";
    function getNumber(num){
       var notValid = num + " not valid";
       num = num.trim().replace(/[^0-9]/g, ""); // replace all none number char
       
        // find the international configration settings
        var r = internationalCodes.filter(x=> 
        x.codes.findIndex(i=>  num.substr(0, i.length)== i) != -1)

       if (r.length<=0) // no internationalCodes configration
             return notValid;
          r = r[0];

        if (num.length<r.minLength)
            return notValid;
          
          
          var resultNum = r.translateTo;
          var code = r.codes.filter(x=> num.substr(0, x.length) == x)[0]
          
          num = num.substr(code.length, num.lengt)

          
          for (var i = 0; i< num.length; i++)
          {

            if (i % seperatorCount == 0)
                resultNum += seperator;
              resultNum += num[i];
          }
               
           return resultNum;
    }
    console.log(getNumber("031(123)123"))
    console.log(getNumber("(0123)123"))
    console.log(getNumber("031.123"))
    console.log(getNumber("31.(123)123"))
    console.log(getNumber("+31.123.123"))
    console.log(getNumber("+31 (123) 123"))
     console.log(getNumber("+50 (123) 123"))
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31