SorryEh
SorryEh

Reputation: 928

validating phone number in Javascript with hyphens

ok So I've tried to validate a phone number script for the past 2 hours but I can't seem to figure out why this isn't working. the Maximum length is 12 and I've already got an if statement for that, that works.

the format would have to be : nnn-nnn-nnnn

         var tele = document.pizza.field03;  //store phone number
         var fone = tele.value               //store values of variable tele in fone
         var acode = "";                    
         var midnum = "";                    
         var lasnum = "";                    
         var hyphen = "";                  
         var hyphen2 ="";                        

   acode=fone.substr(0,3);
   hyphen=fone.substr(3,4);
   midnum=fone.substr(4,7);
   hyphen2=fone.substr(7,8);
   lasnum=fone.substr(8);

       else if (isNaN(acode) )
         {
           errMessages += "<li>Please use integer numbers only</li>\n";
           errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
         }

       else if (isNaN(midnum) )
         {
           errMessages += "<li>Please use integer numbers only</li>\n";
           errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
         }

       else if (isNaN(lasnum) )
         {
           errMessages += "<li>Please use integer numbers only</li>\n";
           errMessages += "<li>ex: 1 2 3 4 5 </li>\n";
         }

EDIT*

else if (hyphen.indexOf('-') ==-1)                  //checking for hyphen
     {
       errMessages += "<li>You need a hyphen after the area code</li>\n"
       errMessages += "<li>ex: areacode-nnn-nnn</li>\n"
     }

   else if (hyphen2.indexOf('-') ==-1)
     {
       errMessages += "<li>You need a hyphen after the middle 3 digits</li>\n";
       errMessages += "<li>ex: 416-mid-1234</li>\n";
     }

what happens is whether I use digits or letters it'll keep popping up the error window.

I want to learn how to do this without using RegEx if possible. Thank you.

Upvotes: 0

Views: 861

Answers (2)

Szilard Muzsi
Szilard Muzsi

Reputation: 1891

The syntax of substr is string.substr(start,length).

You, however, seem to be calling it with string.substr(start,end).

See here for more details

Upvotes: 1

Armatus
Armatus

Reputation: 2191

acode=fone.substr(0,3);
hyphen=fone.substr(3,4);
midnum=fone.substr(4,7);
hyphen2=fone.substr(7,8);
lasnum=fone.substr(8);

The second parameter specifies the length of the string taken, not the "end position". (See reference)

Your variables come out with the values 'nnn', '-nnn', 'nnn-nnnn', '-nnnn' and 'nnnn'.

acode=fone.substr(0,3);
hyphen=fone.substr(3,1);
midnum=fone.substr(4,3);
hyphen2=fone.substr(7,1);
lasnum=fone.substr(8);

Upvotes: 2

Related Questions