【发布时间】:2014-02-04 15:53:44
【问题描述】:
嗨 :) 这是我第一次在这里发帖,但我想不通,应该很简单。我想我已经看了太久了。所以我有一个表单,我正在为它执行表单验证,所有的验证工作都会发送到数据库。
我遇到的小问题是当涉及到电子邮件并确认电子邮件验证时,第一个 if 语句检查文本框是否为空,如果是,我应该收到“需要电子邮件”消息。但是由于第二个 if 语句,我认为 $emailErr 变量会被第二个错误消息覆盖,只有在电子邮件语法无效时才会出现。
因此,如果我将文本框留空,我仍然会收到“语法无效”消息,而不是“需要电子邮件”消息。
我的困惑来自这样一个事实,例如,我的“名字”验证(和所有其他验证)几乎是相同的想法,但它们不会被第二个错误消息覆盖,第二个错误消息也通过使用第二个if 语句。
我将复制我的名字验证代码和电子邮件验证代码,以便您了解我在说什么。任何帮助将不胜感激。如果没有,我肯定最终会弄明白的:)谢谢!
名字验证 - 如果我将文本框留空,我会收到错误消息“需要名字” - 这是正确的。
//Check if the firstname textbox is empty
if (empty($_POST['fname']))
//Show error message
{
$fnameErr = "First name is required";
}
//Check if fname is set
elseif (isset($_POST['fname']))
//Check the text using the test_input function and assign it to $fname
{$fname = test_input($_POST['fname']);}
//Check if first name contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname))
//Show error message & unset the fname variable
{
$fnameErr = "Only letters and white space allowed";
unset($_POST['fname']);
}
else
//Check the text using the test_input function and assign it to $fname
{$fname = test_input($_POST['fname']);}
电子邮件验证 - 如果我将文本框留空,我会收到错误消息“无效的电子邮件格式” - 它应该是“需要电子邮件” - 这是为什么?
//Check if the email textbox is empty
if (empty($_POST['email']))
//Show error message
{
$emailErr = "Email is required";
}
//Check if email is set
elseif (isset($_POST['email']))
//Check the text using the test_input function and assign it to $email
{$email = test_input($_POST['email']);}
//Check if e-mail syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
//Show error message & unset the email variable
{
$emailErr = "Invalid email format";
unset($_POST['email']);
}
else
//Check the text using the test_input function
{$email = test_input($_POST['email']);}
【问题讨论】:
-
说真的,把代码删了,说点别的,不然人家就跑了
-
实际上电子邮件格式不正确,因为它是空白的,所以这是一个问题吗?
-
两件事,1.你为什么不检查
stringlength > 0(这将消除可能的空白字符串。2.Validating email addresses with regex is opening a whole can of worms -
您可能需要考虑使用
\p{L}而不是a-zA-z验证名字,因为 Björn、Paweł 等名字... -
@Yisera OP 仍然需要验证服务器端,前端不能被信任,因为 javascript 可以关闭。
标签: php