0

I have been attempting to validate an australian phone number using javascript however it has been accepting everything. It needs to be 10 numbers long beginning with 0 accepting spaces:
02 4345 2334
and together
0243452334.
I think the regex might be wrong or the code itself

function PhoneNumberVal(form){
    var phoneFormat= /^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$/;  
    var phoneLength = document.getElementById('phone').value.length;

    if(phoneFormat.test(phoneLength)) {
        return true;
    } else {
        alert("Not a valid phone number");
        return false;
    }
}

3 Answers3

0

Your regex is wrong. ^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$ you failed to put the opening parenthesis and you need to change [0-8]{2} to [0-8], since your input contains exactly 10 digits.

^(?:\(0[0-8]\)|0[0-8])[ ]?[0-9]{4}[ ]?[0-9]{4}$

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

Regex? Ha! Now you have two problems.

UPDATE: This version should be final.

Just do this:

function IsAustralianTelephoneNumberValid(a_telephone)
{
    a_telephone = a_telephone.replace(/\s/g, ''); // remove all spaces

    // if is empty OR first char is NOT 0 
    if((a_telephone=='')||(a_telephone.charAt(0)!='0'))
    {
        alert("Not a valid phone number");
        return false;
    }

    // lets save the length of that string before we remove digits
    length_with_digits = a_telephone.length;

    // now string has its digits removed
    a_telephone = a_telephone.replace(/0|1|2|3|4|5|6|7|8|9/g,'');

    // if is nothing, then there was no other characters in string
    // except digits and spaces AND ALSO if the difference of length before the digits
    // removal and now is 10 then we can be sure we had 10 digits and nothing else,
    // so its valid. Any other case is not valid.
    if((a_telephone=='')&&(length_with_digits-a_telephone.length==10))
    {
        alert('ok');
        return true;
    }
    else
    {
        alert("Not a valid phone number");
        return false;
    }
}

http://jsfiddle.net/L7vzL4jm/10/

Community
  • 1
  • 1
Sharky
  • 6,154
  • 3
  • 39
  • 72
0

Use this Regex,

/^\D*0(\D*\d){9}\D*$/

Demo

USER10
  • 939
  • 11
  • 28