使用PHP验证手机的长度

时间:2016-03-21 20:38:43

标签: php validation string-length

我试图验证一个范围内的电话号码的长度。让我们说至少9个字符,但不要超过12个,这样我就可以获得国际电话号码。

我尝试了几件事,但没有一件能奏效。

下面的选项可以正确验证它没有字母,但是我引入的数字长度并不重要,我总是收到错误信息:"你的电话号码需要有9个-11号"即使我引入了9,10或11位数字。

非常感谢

if (empty($_POST["cellphone"])) {
 $cellphoneErr = "Cell Phone is required";
} else {
 $cellphone = test_input($_POST["cellphone"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$cellphone)) {
  $cellphoneErr = "Only numbers allow";
}
 elseif(strlen($_POST["cellphone"] < 9) || strlen($_POST["cellphone"] > 11)){
 $cellphoneErr = "Your phone number needs to have 9-11 numbers";
}
}

2 个答案:

答案 0 :(得分:1)

preg_match()与量词{min,max}一起使用:

if (!preg_match("/^[0-9]{9,11}$/",$cellphone)) {
  $cellphoneErr = "Has to be 9 to 11 numbers.";
}

答案 1 :(得分:0)

elseif(strlen($_POST["cellphone"] < 9) || strlen($_POST["cellphone"] > 11)){

应该是:

elseif(strlen($_POST["cellphone"]) < 9 || strlen($_POST["cellphone"]) > 11){

你的括号错了。