简体   繁体   English

验证电话号码

[英]validating a phone number

如何确定输入的家庭电话号码是否有效(没有区号)?

Regex is the best option for validating a phone number.正则表达式是验证电话号码的最佳选择。

you can use it on the html input tag like this (this may not be supported in all browsers):你可以像这样在 html input 标签上使用它(这可能不被所有浏览器支持):

<input id="phonenum" type="tel" pattern="^\d{3}-\d{4}$" required > 

or you can test a regex string in you code like this (also, this is the correct format for you function above):或者你可以在你的代码中测试一个正则表达式字符串(同样,这是你上面函数的正确格式):

<script type="text/javascript">
     //function\\
     function validPhone(phoneNum) {
         var reg = new RegExp("^\d{3}-\d{4}$");
         if (reg.test(phoneNum)) {
             return "True";
         }
         else {
             return "False";
         }
     }
</script>

and if you want to make it short and sweet and you just need to return a bool value, you can do do this:如果你想让它简短而甜蜜,你只需要返回一个 bool 值,你可以这样做:

<script type="text/javascript">
     //function\\
     function validPhone(phoneNum) {
         var reg = new RegExp("^\d{3}-\d{4}$");
         return reg.test(phoneNum);
     }
</script>

You should only have parenthesis/brackets after an else if statement.您应该只在 else if 语句之后使用括号/方括号。 Not an else statement.不是 else 语句。

Example: If(true){ }else if(true){ }示例:If(true){ }else if(true){ }

Or或者

If(true){
}else{
}

NOT if(true){ }else(){ }不是 if(true){ }else(){ }

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

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