简体   繁体   English

使用JavaScript验证电话号码

[英]Validating phone number with JavaScript

I have a form with three elements. 我有一个包含三个要素的表格。 I want to validate the phone number when the user enters it. 我想在用户输入电话号码时对其进行验证。 If the user moves to the next element and phone number contains and characters which is not numbers I want to display an alertbox. 如果用户移动到下一个元素,并且电话号码包含和不是数字的字符,我想显示一个警报框。

I have written some code but am completely stumped. 我已经写了一些代码,但是完全陷入了困境。 The problem I am having with my function is, that even if I enter only numbers into the phone number element I still get the alert box displayed. 我的功能遇到的问题是,即使我仅在电话号码元素中输入数字,我仍然会看到警告框。 My code looks like this: 我的代码如下所示:

<script type="text/javascript">
function validateForm()
{
checkNr= isNaN(document.forms[0].elements[1])
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
} 
</script>

<form>
  <strong>FULLNAME: </strong><input type="text" / id="name"><br />
  <strong>PHONE NR: </strong><input type="text" id="phone"  onblur="validateForm()" />
  <strong>NATIONALITY</strong><input type="text" id="nat" /><br />
  <input type="button" id="subButton" onclick="calc()" value="Submit" />
</form>

Thank you in advance for all your answers and help. 预先感谢您的所有答复和帮助。

Change 更改

document.forms[0].elements[1]

to

document.forms[0].elements[1].value

You were testing the element itself, not the element's value. 您正在测试元素本身,而不是元素的值。

jsFiddle example jsFiddle示例

BTW, if someone enters a phone number with a dash or parenthesis (eg (555) 123-4567) what do you expect to happen? 顺便说一句,如果有人输入带有破折号或括号的电话号码(例如(555)123-4567),您期望发生什么?

Here you will find many exemple to achieve your goal : 在这里,您会发现许多示例可以实现您的目标:

for example if you can use only number : 例如,如果您只能使用number:

function phonenumber(inputtxt)  
{  
  var phoneno = /^\d{10}$/;  
  if((inputtxt.value.match(phoneno))  
        {  
      return true;  
        }  
      else  
        {  
        alert("message");  
        return false;  
        }  
}

You should do it with a regular expression. 您应该使用正则表达式执行此操作。 See here: 看这里:

A comprehensive regex for phone number validation 用于电话号码验证的综合正则表达式

Validate phone number with JavaScript 使用JavaScript验证电话号码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM