验证POST值是PHP中的电子邮件还是8位数字

时间:2017-03-25 18:20:01

标签: php validation email post numbers

我一直在尝试在PHP中实现POST值的服务器端验证 - 该值应该是有效的电子邮件地址或8位数字。

到目前为止,我得到的是:

<?php

 $username = $_POST["username"];

 if (!filter_var($username, FILTER_VALIDATE_EMAIL) || second-condition-about-8-digit-number-here) {

 header("Location: ../login-error/?&sessionid=$hash&securessl=true");
 die();

 }

?>

我喜欢关于如何实现这一点的一些指导。输入值应为电子邮件地址或8位数字。

2 个答案:

答案 0 :(得分:2)

<?php
$username = $_POST["username"];

if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !preg_match('/^[0-9]{8}$/', $username)) {
    header("Location: ../login-error/?&sessionid=$hash&securessl=true");
    die();
}

?>

答案 1 :(得分:-1)

您需要使用strlen来获取字符串的长度。

因为你只关心数字,所以你可以使用这种方法..

$length = strlen(preg_replace("/[^0-9]/", '', $username));

这会将$length设置为字符串$username中存在的数字字符数。