我一直在尝试使用javascript验证澳大利亚的电话号码,但它已经接受了所有内容。它需要10个数字长,从0接受空格开始:
02 4345 2334
和在一起
0243452334
。
我认为正则表达式可能是错误的或代码本身
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;
}
}
答案 0 :(得分:0)
你的正则表达式错了。 ^0[0-8]{2})\)?[ ]?([0-9]{4})[ ]?([0-9]{4})$
您未能使用左括号,因此您需要将[0-8]{2}
更改为[0-8]
,因为您的输入恰好包含10位数字。
^(?:\(0[0-8]\)|0[0-8])[ ]?[0-9]{4}[ ]?[0-9]{4}$
答案 1 :(得分:0)
正则表达式?哈! Now you have two problems.
更新:此版本应为最终版。
这样做:
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;
}
}
答案 2 :(得分:0)