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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)