如何使用php验证表单并在html中显示错误文本

如何使用php验证表单并在html中显示错误文本,php,html,forms,Php,Html,Forms,我想使用php验证表单,然后将输入保存在json文件中。我使用span类将writer.php中的错误消息回显到html中。但它并没有在html中回显错误文本,而是使用空白页面引用writer.php <head> <title>Data Buku</title> <link rel="stylesheet" type="text/css" href="style.css"> <link href='http://fo

我想使用php验证表单,然后将输入保存在json文件中。我使用span类将writer.php中的错误消息回显到html中。但它并没有在html中回显错误文本,而是使用空白页面引用writer.php

<head>
    <title>Data Buku</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>

<body>
<div class="center">
    <h1>Data Buku</h1>

        <p><span class="error">* required field.</span></p>

        <hr>

        <form action="writer.php" method="post">
            <span class="error"><?php echo $error;?></span>
            <h2>Informasi Pengarang</h2>
            Nama: <br><input type="text" name="nama" id="nama" />
            <span class="error">* <?php echo $namaErr;?></span><br>
            Nomor Telepon: <br><input type="text" name="telepon" id="telepon" />
            <span class="error">* <?php echo $nomorErr;?></span><br>
            e-Mail: <br><input type="email" name="email" id="email" />
            <span class="error">* <?php echo $emailErr;?></span><br>

            <h2>Tulisan</h2>
            Judul: <br><input type="text" name="judul" id="judul" />
            <span class="error">* <?php echo $judulErr;?></span><br>
            Konten: <br><textarea name = "konten" rows="6" cols="50" id="konten"></textarea>
            <span class="error">* <?php echo $kontenErr;?></span><br>
            <input type="submit" id="submit" name = submit value="Create" />
            <input type="reset" id="reset" value="Reset" />
        </form>
</div>      
</body>

布库数据
布库数据
*必填字段


彭加朗信息 Nama:
*
Nomor Telepon:
*
电子邮件:
*
图利桑 朱杜尔:
*
康腾:
*

这是我的php文件

<?php
    // Append new form data in json string saved in json file

    // path and name of the file
$filetxt = 'dataInJson.json';

    // error message
$namaErr = "";
$nomorErr = "";
$emailErr = "";
$judulErr = "";
$kontenErr = "";

    // check if all form data are submited, else output error message
    if(isset($_POST['submit'])) {
    // if form fields are empty, outputs message, else, gets their data
    if(empty($_POST['nama'])) {
        $namaErr = "Write your name";
    }
    if(empty($_POST['telepon'])){
        $nomorErr = "Write the phone number";
    }
    if(empty($_POST['email'])){
        $emailErr = "Write the email";
    }
    if(empty($_POST['judul'])){
        $judulErr = "Write the title";
    }
    if(empty($_POST['konten'])) {
        $kontenErr = "Write the content";
    }
    else {

    // gets and adds form data into an array
    $data = array(
      'nama'=> $_POST['nama'],
      'telepon'=> $_POST['telepon'],
      'email'=> $_POST['email'],
      'judul'=> $_POST['judul'],
      'konten'=> $_POST['konten'],
    );

    // path and name of the file
    $filetxt = 'dataInJson.json';

    $arr_data = array();        // to store all form data

    // check if the file exists
    if(file_exists($filetxt)) {
      // gets json-data from file
      $jsondata = file_get_contents($filetxt);

      // converts json string into array
      $arr_data = json_decode($jsondata, true);
    }

    // appends the array with new form data
    $arr_data[] = $data;

    // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

    // saves the json string in "dataInJson.json"
    // outputs error message if data cannot be saved
    if(file_put_contents('dataInJson.json', $jsondata)){
        echo '<script type="text/javascript">alert("Data has been submitted");</script>';
    }
    else{
        echo 'Tidak dapat menyimpan data di "dataInJson.json"';
    }
  }
}
    else echo 'Form fields not submited';
?>

您的if/else语句是错误的。您的else仅在以下情况下执行!空($_POST['konten'])。
我建议您将错误拉入一个数组,存储在重定向用户的会话中(如果脚本位于不同的文件中),并显示错误数组的内容。如果您在逻辑上有问题,请在此处查看此问题-

除非您使用AJAX解决方案,否则您需要将页面提交给自己,这样所有内容都必须在一个页面上:

<?php
    error_reporting(E_ALL);
    class   ValidateInfo
        {
            public  $errors;
            public  $message;
            public  $data;
            public  function Check($payload = array(),$type = "error",$mess = "unknown",$validate = array())
                {
                    $trimmed                =   trim($payload[$type]);

                    if(!empty($validate)) {
                            // Strip out everything but numbers and letters and a couple of symbols.
                            if(in_array('digits',$validate) && in_array('letters',$validate)) {
                                    $this->data[$type]  =   preg_replace('/[^0-9a-zA-Z\s\-\_]/','',$trimmed);
                                }
                            // Strip out all but numbers
                            elseif(in_array('digits',$validate)) {
                                    $this->data[$type]  =   preg_replace('/[^0-9]/','',$trimmed);
                                }
                            // Strip out letters
                            elseif(in_array('letters',$validate)) {
                                    $this->data[$type]  =   preg_replace('/[^a-zA-Z\s\-\_]/','',$trimmed);
                                }
                            // Re-assign data type to consolidate
                            $this->data[$type]          =   (!isset($this->data[$type]))? $trimmed:$this->data[$type];

                            // Check if data is an email
                            if(in_array('email',$validate)) {
                                    $this->data[$type]  =   (filter_var($this->data[$type], FILTER_VALIDATE_EMAIL))? $this->data[$type]:'';
                                }

                            // Strip out html tags
                            if(in_array('strip',$validate)) {
                                    $this->data[$type]  =   strip_tags($this->data[$type]);
                                }
                        }

                    if(!isset($this->data[$type]))
                        $this->data[$type]  =   $trimmed;

                    $this->errors[$type]    =   (empty($this->data[$type]))? 1:0;
                    $this->message[$type]   =   $mess;
                }
        }

    // Creat instance of info processor
    $info   =   new ValidateInfo(); 

    // check if all form data are submited, else output error message
    if(isset($_POST['submit'])) {

            // Checks empty fields
            $info->Check($_POST,'nama','Write your name',array('letters','digits'));
            $info->Check($_POST,'telepon','Write the phone number',array('digits'));
            $info->Check($_POST,'email','Write the email',array('email'));
            $info->Check($_POST,'judul','Write the title',array('letters','digits'));
            $info->Check($_POST,'konten','Write the content', array('letters','digits','strip'));

            if(array_sum($info->errors) == 0) {

                    // path and name of the file
                    $filetxt    =   'dataInJson.json';

                    // Assign stored data
                    $data       =   $info->data;

                    // path and name of the file
                    $filetxt    =   'dataInJson.json';

                    // to store all form data
                    $arr_data   =   array();        

                    // check if the file exists
                    if(file_exists($filetxt)) {
                            // gets json-data from file
                            $jsondata   =   file_get_contents($filetxt);

                            // converts json string into array
                            $arr_data   =   json_decode($jsondata, true);

                            // appends the array with new form data
                            $arr_data[] =   $data;

                            // encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
                            $jsondata   =   json_encode($arr_data, JSON_PRETTY_PRINT);

                            // saves the json string in "dataInJson.json"
                            // outputs error message if data cannot be saved
                            if(file_put_contents('dataInJson.json', $jsondata)) {
                                    $info->errors['success']    =   true; ?>
                                <script type="text/javascript">
                                    alert("Data has been submitted");
                                </script>
                            <?php }
                            else {
                                    $info->message['general']['put_file']   =   'Tidak dapat menyimpan data di "dataInJson.json"';
                                }
                        }
                    else {
                            $info->message['general']['bad_file']   =   'No file exists';
                        }
                }
        }
    else 
        $info->message['general']['submit'] =   'Form fields not submited'; ?>
<head>
<title>Data Buku</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Ribeye+Marrow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' type='text/css'>
</head>
<style>
.error { color: red; clear: left; float: left; display: inline-block; width: 100%; font-size: 12px; }
input,
textarea    { float: left; clear: left; display: inline-block; font-size: 20px; color: #333; padding: 10px; }
label   { font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: #888; float: left; clear: left; display: inline-block; }
div.roadie  { width: 500px; border-bottom: 1px solid #CCC; display: inline-block; float: left; clear: both; padding: 10px; }
</style>
<body>
<div class="center">
<h1>Data Buku</h1>

    <?php if(isset($info->errors['success'])) { ?>
        <h2>Thank you!</h2>
    <?php } else { ?>
    <p><span class="error">* required field.</span></p>
    <?php } ?>
    <hr>
    <form action="" method="post">
        <?php if(isset($info->message['general'])) {
            foreach($info->message['general'] as $_error) { ?>
            <span class="error">* <?php echo $_error; ?></span><br>
            <?php
                }
        } ?>

        <h2>Informasi Pengarang</h2>
        <div class="roadie">
            <label for="nama">Nama:</label>
            <input type="text" name="nama" id="nama"<?php if(isset($info->data['nama'])) { ?> value="<?php echo strip_tags($info->data['nama']); ?>" /><?php } ?>
            <?php if(isset($info->errors['nama']) && $info->errors['nama'] == 1) { ?><span class="error">* <?php echo $info->message['nama']; ?></span><?php } ?>
        </div>
        <div class="roadie">
            <label for="telepon">Nomor Telepon:</label>
            <input type="text" name="telepon" id="telepon"<?php if(isset($info->data['telepon'])) { ?> value="<?php echo strip_tags($info->data['telepon']); ?>"<?php } ?> />
        <?php if(isset($info->errors['telepon']) && $info->errors['telepon'] == 1) { ?><span class="error">* <?php echo $info->message['telepon']; ?></span><?php } ?>
        </div>
        <div class="roadie">
            <label for="email">e-Mail:</label>
            <input type="email" name="email" id="email"<?php if(isset($info->data['email'])) { ?> value="<?php echo strip_tags($info->data['email']); ?>"<?php } ?> />
        <?php if(isset($info->errors['email']) && $info->errors['email'] == 1) { ?><span class="error">* <?php echo $info->message['email']; ?></span><br><?php } ?>
        </div>
        <div class="roadie">
        <h2>Tulisan</h2>
            <label for="judul">Judul:</label>
            <input type="text" name="judul" id="judul"<?php if(isset($info->data['judul'])) { ?> value="<?php echo strip_tags($info->data['judul']); ?>"<?php } ?> />
        <?php if(isset($info->errors['judul']) && $info->errors['judul'] == 1) { ?><span class="error">* <?php echo $info->message['judul']; ?></span><?php } ?>
        </div>
        <div class="roadie">
            <label for="konten">Konten:</label>
            <textarea name = "konten" rows="6" cols="50" id="konten"><?php if(isset($info->data['konten'])) {  echo strip_tags($info->data['konten']); } ?></textarea>
        <?php if(isset($info->errors['konten']) && $info->errors['konten'] == 1) { ?><span class="error">* <?php echo $info->message['konten']; ?></span><br><?php } ?>
        </div>
        <input type="submit" id="submit" name = submit value="Create" />
        <input type="reset" id="reset" value="Reset" />
    </form>
</div>      
</body>

警报(“数据已提交”);
布库数据
.错误{颜色:红色;清除:左侧;浮动:左侧;显示:内联块;宽度:100%;字体大小:12px;}
输入,
text区域{浮点:左;清除:左;显示:内联块;字体大小:20px;颜色:#333;填充:10px;}
标签{字体系列:Arial,Helvetica,无衬线;字体大小:14px;颜色:#888;浮点:左;清除:左;显示:内联块;}
div.roadie{宽度:500px;边框底部:1px实心#CCC;显示:内联块;浮动:左;清除:两者;填充:10px;}
布库数据
非常感谢。
*必填字段


*
彭加朗信息 非农产品市场准入: 值=”“/> * Nomor Telepon: 值=”“/> * 电邮: 值=”“/> *
图利桑 朱杜尔: 值=”“/> * 康腾: *

这些是在同一个页面上吗?不,有两个页面,html和phpOk。我将它们合并为一个页面,因此当我问这个问题时,json文件中的错误仍然有效。我只是无法验证我的表单什么部分没有进行验证?下面是上述验证的工作演示:我添加了表单重新插入已填写答案的功能,这样不仅可以在提交时验证数据,用户已填写的数据的任何部分都将再次填写字段,这样人们就不必从头重写表单。请看演示,提供一个类要比OP的代码复杂得多。你认为他怎么能理解呢?这是一个13行的类,user3396在其过程代码中实现了所有功能。这个类只需少1/3行就可以完成同样的事情,而且可以说要复杂得多。