【问题标题】:Validating contact form in PHP在 PHP 中验证联系表单
【发布时间】:2013-08-29 22:31:46
【问题描述】:

我有一个联系表格,需要在 PHP 中进行验证,以检查每个字段是否填写正确。

这是我所拥有的:

//Post fields
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_services = $_POST['services'];
$field_it = $_POST['it'];
$field_location = $_POST['location'];
$field_message = $_POST['message'];


//mail_to omitted 


//Validation of contact form

$errormessage = '';
if($field_name == ''){

$errormessage += 'You have not entered your Name\n';
}

if($field_email == ''){

$errormessage += 'You have not entered your Email Address\n';
}

if($field_services == ''){

$errormessage += 'You have not chosen the service you require\n';
}

if($field_it == ''){

$errormessage += 'You have not chosen the Date of your event\n';
}

if($field_location == ''){

$errormessage += 'You have not entered the location of your event\n';
}


if($errormessage != ''){ ?>

<script language="javascript" type="text/javascript">
    alert('The following fields have not neen entered correctly\n<?php echo "$errormessage" ?>');
    window.location = 'contact.html';
</script>
<?php } 



if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
    alert('Thank you for the message. We will contact you shortly.');
    window.location = 'contact.html';
</script>
<?php
}


else { ?>
<script language="javascript" type="text/javascript">
    alert('Message failed. Please, send an email to s_ejaz@live.co.uk');
    window.location = 'contact.html';
</script>
<?php
}
?>

当我尝试提交一个空的联系表单时,这没有任何作用,它应该提醒用户未填写但没有填写的特定字段。它只是把我带到一个空白的白页。

谁能帮我找出哪里出错了?

【问题讨论】:

  • 在任何验证之前开始发送邮件
  • 空白页?你的错误日志是怎么说的?

标签: php html validation contact-form


【解决方案1】:

另外,您可以使用修剪功能删除任何空格。

trim($_POST['name'])...

【讨论】:

    【解决方案2】:

    您应该使用strlen()isset() 检查是否从表单收到任何数据。

    例子:

    if(!isset($_POST['name']) || strlen($_POST['name']) < 1){
        $errormessage .= 'You have not entered your Name\n';
    }
    

    【讨论】:

    • 不,我按照你说的把它改成了.=
    • 你不应该验证这个答案,因为它会导致其他人犯同样的错误
    【解决方案3】:

    尝试使用$errormessage.='Some text\n'; 而不是$errormessage+='Some text\n';
    使用“+”而不是“.”,PHP 将变量$errormessage视为一个数字,断言失败。

    【讨论】:

      【解决方案4】:

      不要像 $field_services == '' 这样将变量与空字符串进行比较,而是使用 empty()isset()

      if(!empty($field_services))if(isset($field_services))

      另一个问题是您使用 + 连接字符串,如果您使用的是 javascriptjavaC# 等,这是正确的。而不是 PHP

      使用 PHP 连接变量:

       $var='Hello';
       $var.=' World !'
      
       echo $var;// Hello World !
      

      所以你的代码应该是:

       if(empty($_POST['name'])){
         $errormessage .= 'You have not entered your Name\n';
      }
      

      【讨论】:

      • 是的 :p 太习惯 JavaScript....= 它是
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多