2013-04-05 101 views
0

我是JavaScript新手,我一直在做一些创建HTML和JavaScript表单的工作。在这项工作中,我一直试图根据输入到前一个字段中的文本来验证输入的格式。输入改变文本框格式

我一直在尝试的是,如果国家'澳大利亚'进入'国家'文本框比'电话'文本框被限制为格式(00)00000000,并且如果它是任何其他国家'电话'文本框必须采用国际号码格式,包括例如+和国家代码+61等

我已经做了这么多,到目前为止函数:

<script> 
document.getElementById('txttelephone').onchange = function() 
{ 
var num1 = document.getElementById('txttelephone').value, 
    country = document.getElementById('txtcountry').value, 
    regex; 

if (country == "Australia" || country == "australia") 
{ 
    regex = /\(\d{2}\)\d{8}/; 
} 
else 
{ 
    regex = /\+\d{15}/; 
} 
if (!num1.match(regex)) 
{ 
    alert('That is not a correct telephone number'); 
} 
} 
</script> 

这仅仅是我做的“电话”文本框中的字符串长度限定为12个字符,但我仍然功能尚未验证以确保(00)00000000格式的区号包含在括号内,并且如果国家不是澳大利亚(包括国家代码在内的国际号码),则还要验证是否包含a +。

下面是HTML我不得不使用功能上:

<b>Country:</b> <input type="text" id="txtcountry" name="country"> 
<br> 
<b>Telephone:</b> <input type="text" id="txttelephone" name="telephone"> 

任何帮助将不胜感激!

+0

检查出[regex](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – 2013-04-05 14:08:42

回答

1

你需要的是一个regular expression来测试电话号码是否符合你想要的格式。

这里是一个为澳大利亚号码/\(\d{2}\)\d{8}/。正则表达式以/开头和结尾,然后它将匹配开头括号\(后跟两个数字\d{2}结束括号\)和8个绝对位数\d{8}

所以你的功能可能会成为这个

//changed to onchange event of `txttelephone` 
document.getElementById('txttelephone').onchange = function(){ 
    var num1 = document.getElementById('txttelephone').value, //added .value here 
     country = document.getElementById('txtcountry').value, 
     regex; 
    if(country == "Australia" || country == "australia"){ 
     regex = /\(\d{2}\)\d{8}/; 
    } else { 
     regex = /\+\d{15}/;   
    } 

    if(!num1.match(regex)){ //If there was not a match for your number format 
     alert("thats not a ruddy telephone number!"); 
    } 
} 

作为一个侧面说明,我强烈建议你不要让用户“免费”,在输入自己的国家的任何错别字意味着即你需要你的逻辑是行不通的用户输入澳大利亚或澳大利亚,没有别的可以做,Dropdowns是为这个场景发明的:)。

+0

+1表示为国家/地区名称使用下拉菜单。当我正在阅读这个问题时,我想到了这个问题,但忘了将它写在我的答案中。 – Travesty3 2013-04-05 14:32:07

+0

是的,我也考虑过使用下拉列表来考虑错字。另外我的JavaScript似乎并没有工作,我已更新它在我原来的帖子,所以你可以找到我的错误。顺便谢谢你的帮助! – bigsenator 2013-04-05 14:42:06

+0

@ user2244784对不起,我的错误,因为我修改你的函数的方式,它现在应该真的在电话领域的onchange事件上运行。请在我的答案中看到修改后的代码,然后再去:) – 2013-04-05 14:57:33

0

尝试类似这样的事情。这不是测试,所以正则表达式可能不完全正确,但至少应该帮助:

document.getElementById('myform').onsubmit = function(event) { 
    var country = document.getElementById('txtcountry').value; 
    var regex = /^\+\d{1,2}\(\d{2,3}\)\d{7,8}$/; 
    if (country.toLowerCase() == 'australia') { 
     // make the international code optional 
     regex = /^(\+\d{1,2})?\(\d{2,3}\)\d{7,8}$/; 
    } 

    var phone = document.getElementById('txttelephone').value; 
    if (!phone.test(regex)) { 
     event.preventDefault(); 
     alert('Bad phone number!'); 
     return false; 
    } 
}; 

这将检查值当他们尝试提交表单。如果他们给出了错误的值,它会显示一条错误消息并阻止提交。

另外,正如@MarkWalters建议的那样,我将使用下拉菜单替代国家/地区名称的文本字段。不仅拼写错误会破坏你的逻辑,但是如果用户留下错字,并且你需要搜索国家“澳大利亚”的所有用户,你可能会错过错误输入错误的用户。