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


How to validate form with php and show the error text in html

我想使用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>

这是我的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';
?>

除非你做了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>

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