简体   繁体   English

如何验证 HTML 表单中的电话号码

[英]How to validate phone number in HTML form

I have a form and would like to see if the user filled the input with a correct number or not.我有一个表格,想看看用户是否用正确的数字填写了输入。 The number must contains 10 digits and the two first digits should be equal to 05 or 06 .该号码必须包含 10 位数字,并且前两位数字应等于0506 Can anyone help me how to do this in PHP or in JavaScript please?任何人都可以帮助我如何在 PHP 或 JavaScript 中执行此操作吗?

According to comments and example phone number that you given, this code will validating number of digits and first two numbers of your country, i just replaced + with 0, for sure they won't enter plus.根据您提供的评论和示例电话号码,此代码将验证您所在国家/地区的位数和前两个号码,我只是将 + 替换为 0,以确保他们不会输入加号。

$tel = '0512345678';

if(preg_match("/^0[5|6][0-9]{8}$/", $tel)) {
    echo "valid";
} else {
    echo "invalid";
}

Would you like to validate the phone number on the server or in the client (user's web browser)?您想在服务器上还是在客户端(用户的 Web 浏览器)中验证电话号码? In the first case you should use PHP, in the latter case a JavaScript function.在第一种情况下,您应该使用 PHP,在后一种情况下,您应该使用 JavaScript 函数。

PHP: PHP:

function isValidPhoneNumber($number) {
  return preg_match('/^0[5|6][0-9]{8}$/', $number);
}

JavaScript: JavaScript:

function isValidPhoneNumber(number) {
  return /^0[5|6][0-9]{8}$/.test(number);
}

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

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