0

I'm doing some form validation for a phone number. I only need to find out that it is only numbers or spaces in the phone field. The below checks only for [0-9], which I used in another function, but when I try to reverse it to /\D/.test(phoneChk) (which apparently is the reverse of d) it doesn't seem to work anymore? I am new to javascript, and definitely new to RegEx so am trying to find a simple way to do this. I know there is plenty of examples on the stackoverflow of RegEx, but none seem to be working within the if statement (at least that I can work out).

function fnCheckPhone(strName) {
    strName.style.background = "#FFFFFF";
    var phoneChk = strName.value;
    if (phoneChk == "" || /\d/.test(phoneChk)) {
        strName.style.background = "#FBEC5D";
        return false
    }
    else {return true}

Any help would be appreciated....

Danrex
  • 1,657
  • 4
  • 31
  • 44
  • It is perfectly normal to format telephone numbers with parenthesis and hyphens, and to start it with a `+` character to indicate an international dialing prefix. Don't be overly restrictive in what you allow people to type when you ask for a phone number. – Quentin May 21 '14 at 10:28
  • I'm trying not to be I just don't want letters. – Danrex May 21 '14 at 10:31
  • Can you create a jsfiddle foer it plz – SSS May 21 '14 at 10:32
  • If all you want is simply not letters, you could just replace \d with \W. But that would still allow anything that isn't an a-z letter. I'd certainly recommend using one of the examples from other topics. – Søren Ullidtz May 21 '14 at 10:37
  • This worked - http://www.w3resource.com/javascript/form/phone-no-validation.php – Danrex May 21 '14 at 10:40

1 Answers1

0

I found the answer here - http://www.w3resource.com/javascript/form/phone-no-validation.php

Basically I used this code.

function phonenumber(inputtxt)  
{  
    var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;  
    if((inputtxt.value.match(phoneno))  
    {  
        return true;  
    }  
    else  
    {  
        alert("message");  
        return false;  
    }  

}

Danrex
  • 1,657
  • 4
  • 31
  • 44
  • 1
    I would recommend being careful using that validation. You may not want to prevent users from submitting, but only display a warning if it doesn't validate. You'll need to validate the phone number server side anyway. Phone numbers can come in all shapes and size: http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation – Søren Ullidtz May 21 '14 at 10:44