doukang7486 2014-05-18 13:53
浏览 43
已采纳

如果提交表单,则显示错误

I'm wanting my form to show an error such as "Enter first name" if the field has not being filled in. I have got to right code(I think) to do this but it is showing the error when the page is first loaded. I want it to be displayed when the form has been submitted.

    <div class="Row">
<div class="Lable">First Name:</div> <!--End of Lable-->
<div class="input">
<input type="text" id="firstname" class="detail" name="firstname" placeholder="First Name"  />
</div> <!--End input-->
</div> <!--End row-->
<span class="error">* <?php echo $nameErr;?></span>

The PHP validation is

 if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
 $nameErr = "Name is required";
} else {
 $firstname = test_input($_POST["name"]);
 // check if name only contains letters and whitespace
 if (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
   $nameErr = "Only letters and white space allowed"; 
 }
}

Thanks

  • 写回答

3条回答 默认 最新

  • douzhuanqian8244 2014-05-18 14:27
    关注

    I would double check the form with PHP and JavaScript

    For the javascript part add this line to your form, so the function validate() will run before the forms content will be sent to the server.

    <form onsubmit="validate()">
    

    Then you can add a javascipt function to your document like this:

    function validate() {
      if (/*check if fields are filled out properly*/) {
        this.submit();
      } else {
        // show message here when fields are missing
    
        return false; // this line is important otherwise the form gets submitted anyway
      }
    }
    

    For the PHP part it is enough to check for the differnt fields with isset()

    This would look like this:

    $formOK = true;
    if (!isset($_POST["field-name-1"]) || $_POST["field-name-1"] == "") {
      echo "field-1 is missing";
      $formOK = false
    }
    if (!isset($_POST["field-name-2"]) || $_POST["field-name-2"] == "") {
      echo "field-2 is missing";
      $formOK = false
    }
    
    if (formOK) {
      echo "everything is fine";
      // do something with your form data
    }
    

    To double check is definitly the best way because first of all you are not having so many requests and the javascript is more flexible in is reactions and speed but the PHP will provide you the guarantee that nothing will go wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化