Javascript 如何使用javascript验证电话号码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10616314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:10:22  来源:igfitidea点击:

How do I validate a phone number with javascript?

javascriptvalidation

提问by user1395909

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.

有比我更聪明的人能帮我完成这个功能吗?它的目的是验证表单中的文本输入,一个只接受 0-9、破折号和点的电话号码字段。HTML 很好地调用了该函数。

function validateFeedback() {
    var phone = document.getElementById("phone");
    var validNumber = "0123456789.-";
    for (i = 0; i < phone.length; i++); {
        if (validNumber.indexOf(phone.charAt(i)) == -1); {
            alert("You have entered an invalid phone number");
            return false;
        }
    }
    return true;
}

Thanks so much for any help.

非常感谢您的帮助。

回答by Ji?í Herník

Regular expressions should help ;)

正则表达式应该有帮助;)

I'm sorry I haven't tried to run this code, but it should be OK.

很抱歉我没有尝试运行此代码,但应该没问题。

function validateFeedback(){
    var phone = document.getElementById("phone");
    var RE = /^[\d\.\-]+$/;
    if(!RE.test(phone.value))
    {
        alert("You have entered an invalid phone number");
        return false;
    }
    return true;
}

回答by Aleksandrenko

try like this:

试试这样:

function validateFeedback()
    {
    var phone = document.getElementById("phone");
    var validNumber = "0123456789.-";


    for(i = 0; i < phone.length; i++) {
            if(validNumber.indexOf(phone.charAt(i)) == -1) {
                    alert("You have entered an invalid phone number");
                    return false;
                }
            }

        return true;
    }

there are ;out of place ...

空间不足 ...

回答by JDev

Try this one

试试这个

function validateFeedback(value) {
    var length = value.length;
    chk1="1234567890()-+ ";
    for(i=0;i<length;i++) {
        ch1=value.charAt(i);
        rtn1=chk1.indexOf(ch1);
        if(rtn1==-1)
            return false;
        }
        return true;
    }

回答by Nicolas BADIA

I think you should use a regex to do this. Something link this:

我认为你应该使用正则表达式来做到这一点。东西链接这个:

function validateFeedback() {
  var phone = document.getElementById("phone").value;
  var reg = new RegExp("[0-9 .-]*"); 

  return reg.test(phone);
}

回答by RobG

If the text input is in a form, you can reference it more directly using the form id and the element id:

如果文本输入在表单中,您可以使用表单 id 和元素 id 更直接地引用它:

var phone = document.<formId>.phone;

What you want to test is the value of the element, so you need:

您要测试的是元素的值,因此您需要:

var phone = document.<formName>.phone.value;

Since the function is probably called from a submit listener on the form, you can make things more efficient using:

由于该函数可能是从表单上的提交侦听器调用的,因此您可以使用以下方法提高效率:

<form onsubmit="return validateFeedback(this);" ...>

It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.

在我看来,电话号码只有数字,而不是“-”或“。” 字符,所以你应该只测试数字 0-9。

So the function can be like:

所以函数可以是这样的:

function validateFeedback(form) {
  var phoneValue = form.phone.value;

  // Use a regular expression to validate the value
  // is only digits
  if (/\D/.test(phoneValue) {
    // value contains non-digit characters
    // advise user of error then
    return false;
  }
}

you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.

您可能还想测试长度是否合理,但请注意,不同地方的电话号码长度不同,具体取决于位置和使用的区号或国家/地区代码,以及该号码是用于移动电话、固定电话还是其他电话。

回答by GodLesZ

I would prefer to use regular expressions for something like this. Please look at my modified version of your function which should work in all major browsers without any framework.

我更喜欢使用正则表达式来处理这样的事情。请查看我修改后的函数版本,它应该可以在所有主流浏览器中运行,无需任何框架。

function validateFeedback() {
    // Get input
    var phone = document.getElementById("phone"),
        // Remove whitespaces from input start and end
        phone = (phone || '').replace(/^\s+|\s+$/g, ''),
        // Defined valid charset as regular expression
        validNumber = "/^[0123456789.-]+$/";

    // Just in case the input was empty
    if (phone.length == 0) {
        // This depends on your application - is an empty number also correct?
        // If not, just change this to "return false;"
        return true;
    }

    // Test phone string against the regular expression
    if (phone.match(validNumber)) {
        return true;
    }

    // Some invalid symbols are used
    return false;
}

回答by yanddam

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