空字段和错误消息的PHP表单验证

时间:2017-07-31 06:49:46

标签: php forms validation

我不确定我做错了什么。我试图创建一个简单的表单,如果字段为空则不会上传到MySQL数据库。我在表格中也有一些基本的验证。但是,当我点击“保存'空白表单上传到数据库,我也没有收到每个字段的错误消息,因为我已突出显示它们。

我很欣赏有关我犯错误的建议。

这是我的PHP代码:

<?php 

$firstNameError = $lastNameError = $idNumberError = $mobileNumberError = $emailError = $birthDateError = $languageTypeError = $interestError = "";
$firstName = $lastName = $idNumber = $mobileNumber = $email = $birthDate = $languageType = $interest = "";

if(isset($_POST['submit'])) {

    include 'dbconnect.php';

    try {

        $sql = "INSERT INTO members SET 
                firstName = :firstName,
                lastName = :lastName,
                idNumber = :idNumber,
                mobileNumber = :mobileNumber,
                email = :email,
                birthDate = :birthDate,
                languageType = :languageType,
                interest = :interest,
                created = :created";

        $stmt = $conn->prepare($sql);

        if (empty($_POST["firstName"])) {
            $firstNameError = "First Name is Required Please";
        } else { 
            $firstName = clean_data($_POST["firstName"]);
                if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
                    $firstNameError = "Only letters and white space allowed";
                }
        }
        if (empty($_POST["lastName"])) {
            $lastNameError = "Last Name is Required Please";                
        } else { 
            $lastName = clean_data($_POST["lastName"]);
                if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
                    $lastNameError = "Only letters and white space allowed";
                }
        }
        if (empty($_POST["idNumber"])) {
            $idNumberError = "ID Number is Required Please";                
        } else { 
            $idNumber = clean_data($_POST["idNumber"]);
            if (!preg_match("/^[0-9]{13}$/",$idNumber)) {
                    $idNumberError = "ID must be exactly 13 digits and no white spaces or other characters";
                }
        }
        if (empty($_POST["mobileNumber"])) {
            $mobileNumberError = "Mobile Nr is Required Please";                
        } else { 
            $mobileNumber = clean_data($_POST["mobileNumber"]);
            if (!preg_match("/^[0-9]{10}$/",$mobileNumber)) {
                    $mobileNumberError = "Your phone nr must be exactly 10 digits and no white spaces or other characters";
                }
        }
        if (empty($_POST["email"])) {
            $emailError = "Email is Required Please";               
        } else { 
            $email = clean_data($_POST["email"]);
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $emailError = "Please enter a valid email address";
            }
        }
        if (empty($_POST["birthDate"])) {
            $birthDateError = "Birth Date is Required Please";              
        } else { 
            $birthDate = clean_data($_POST["birthDate"]);
            list($dd,$mm,$yyyy) = explode('-',$birthDate);
            if (!checkdate($yyyy,$mm,$dd)) {
                $birthDateError = "Please use the format YYYY-MM-DD";
            }
        }
        if (empty($_POST["languageType"])) {
            $languageTypeError = "Languge Type is Required Please";             
        } else { 
            $languageType = clean_data($_POST["languageType"]);
        }
        if (empty($_POST["interest"])) {
            $interestError = "Interest is Required Please";             
        } else { 
            $interest = clean_data($_POST["interest"]);
        }

        $stmt->bindParam(':firstName', $firstName);
        $stmt->bindParam(':lastName', $lastName);
        $stmt->bindParam(':idNumber', $idNumber);
        $stmt->bindParam(':mobileNumber', $mobileNumber);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':birthDate', $birthDate);
        $stmt->bindParam(':languageType', $languageType);
        $stmt->bindParam(':interest', $interest);

        $created = date('Y-m-d H:i:s');
        $stmt->bindParam(':created', $created);

        if($stmt->execute()){
            echo "<div class='alert alert-success'>Member was saved.</div>";
        } else {
            echo "<div class='alert alert-danger'>Unable to save this member.</div>";
        }
    }

    catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }

}

function clean_data($data) {

    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;

}

&GT;

这是我的HTML代码:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <table class='table table-hover table-responsive table-bordered'>
        <tr>
            <td>First Name: *</td>
            <td><input type='text' name='firstName' class='form-control' /></td>
        </tr>
        <tr>
            <td>Last Name: *</td>
            <td><input type='text' name='lastName' class='form-control' /></td>
        </tr>
        <tr>
            <td>ID Number: *</td>
            <td><input type='text' name='idNumber' class='form-control' /></td>
        </tr>
        <tr>
            <td>Mobile Number: *</td>
            <td><input type='text' name='mobileNumber' class='form-control' /></td>
        </tr>
        <tr>
            <td>Email: *</td>
            <td><input type='text' name='email' class='form-control' /></td>
        </tr>
        <tr>
            <td>Birth Date</td>
            <td><input type='text' name='birthDate' class='form-control' /></td>
        </tr>
        <tr>
            <td>Language</td>
            <td>

                <select class="form-control" name="languageType">

                  <option>Select One...</option>
                  <option>Afrikaans</option>
                  <option>English</option>
                  <option>Zulu</option>
                  <option>Xhosa</option>
                  <option>Venda</option>
                  <option>French</option>

              </select>
            </td>
        </tr>
        <tr>
            <td>Interest</td>
            <td>

                <select class="form-control" name="interest">

                  <option>Select One...</option>
                  <option>Golf</option>
                  <option>Rugby</option>
                  <option>Tennis</option>
                  <option>Cricket</option>
                  <option>Swimming</option>
                  <option>Hiking</option>
                  <option>Surfing</option>
                  <option>Movies</option>
                  <option>Swords</option>

                </select>

            </td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type='submit' name='submit' value='Save' class='btn btn-primary' />
                <a href='index.php' class='btn btn-danger'>Back to view members</a>
            </td>
        </tr>
    </table>
</form>

6 个答案:

答案 0 :(得分:2)

除非我弄错了(我经常这样做),否则在尝试写入数据库之前,您似乎没有测试是否有错误消息。您应该首先执行所有数据验证,然后将sql语句放在try / catch中,但前提是所有错误都评估为false。如果你认为你可以自己重新排列,那就去吧。如果您需要帮助,请告诉我。

另一个提示,在开头设置另一个名为$error = false;的变量,然后如果任何错误消息被触发,则将其设置为true。然后,对于数据库写入,您只需要查看if($error == true) ...

答案 1 :(得分:1)

您正在为每个不成功的字段名称分配错误字符串。

但是,不要在任何地方使用它。

将代码修改为:

var msg = $('.mail-icon');
var form = $('.form-box');
$("body").on("click touchstart", ".contact-box .mail-icon", function(e) {
    e.stopPropagation();
    form.fadeToggle();
    return false;
});

答案 2 :(得分:0)

&#13;
&#13;
     <form action="" method="post">
     <table class='table table-hover table-responsive table-bordered'>
                        <tr>
                            <td>First Name: *</td>
                            <td><input type='text' name='firstName' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Last Name: *</td>
                            <td><input type='text' name='lastName' class='form-control' required /></td>
                        </tr>
                        <tr>
                            <td>ID Number: *</td>
                            <td><input type='text' name='idNumber' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Mobile Number: *</td>
                            <td><input type='text' name='mobileNumber' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Email: *</td>
                            <td><input type='text' name='email' class='form-control' required /></td>
                        </tr>
                        <tr>
                            <td>Birth Date</td>
                            <td><input type='text' name='birthDate' class='form-control' required/></td>
                        </tr>
                        <tr>
                            <td>Language</td>
                            <td>
    
                                <select class="form-control required" name="languageType" required>
    
                                  <option>Select One...</option>
                                  <option>Afrikaans</option>
                                  <option>English</option>
                                  <option>Zulu</option>
                                  <option>Xhosa</option>
                                  <option>Venda</option>
                                  <option>French</option>
    
                              </select>
                            </td>
                        </tr>
                        <tr>
                            <td>Interest</td>
                            <td>
    
                                <select class="form-control" name="interest" required>
    
                                  <option>Select One...</option>
                                  <option>Golf</option>
                                  <option>Rugby</option>
                                  <option>Tennis</option>
                                  <option>Cricket</option>
                                  <option>Swimming</option>
                                  <option>Hiking</option>
                                  <option>Surfing</option>
                                  <option>Movies</option>
                                  <option>Swords</option>
    
                                </select>
    
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <input type='submit' name='submit' value='Save' class='btn btn-primary' />
                                <a href='index.php' class='btn btn-danger'>Back to view members</a>
                            </td>
                        </tr>
                    </table>
                    </form>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

在POST之前进行此验证会更简单:

<td><input type='text' name='firstName' class='form-control' required placeholder="Enter a valid First Name :)"/></td>

地点&#34;必需&#34;每个必填输入字段的属性。此验证在POST之前完成,因此您不需要从后端进行另一次验证。

答案 4 :(得分:0)

所以我添加了“抛出新异常”#39;在php代码中阻止数据提交给db。下面我强调了改变。

if (empty($_POST["firstName"])) {
                        *throw new Exception ("First Name is a Required Field");*
                    } else { 
                        $firstName = clean_data($_POST["firstName"]);
                            if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
                                *throw new Exception ("Only letters and whitespace allowed in First Name");*
                            }
                    }
                    if (empty($_POST["lastName"])) {
                        *throw new Exception ("Last Name is a Required Field");*                
                    } else { 
                        $lastName = clean_data($_POST["lastName"]);
                            if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
                                *throw new Exception ("Only letters and whitespace allowed in Last Name");*
                            }
                        }
                    if (empty($_POST["idNumber"])) {
                        *throw new Exception ("ID Number is a Required Field");*            
                    } else { 
                        $idNumber = clean_data($_POST["idNumber"]);
                        if (!preg_match("/^[0-9]{13}$/",$idNumber)) {
                                *throw new Exception ("ID Number may only contain numbers and may only be 13 digits long");*
                            }
                    }
                    if (empty($_POST["mobileNumber"])) {
                        *throw new Exception ("Mobile Number is a Required Field");*                
                    } else { 
                        $mobileNumber = clean_data($_POST["mobileNumber"]);
                        if (!preg_match("/^[0-9]{10}$/",$mobileNumber)) {
                                *throw new Exception ("Mobile Number may only contain numbers and may only be 10 digits long");*
                            }
                    }
                    if (empty($_POST["email"])) {
                        *throw new Exception ("Email is a Required Field");*                
                    } else { 
                        $email = clean_data($_POST["email"]);
                        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            *throw new Exception ("Please make sure you entered a valid email");*
                        }
                    }
                    if (empty($_POST["birthDate"])) {
                        *throw new Exception ("D.O.B. is a Required Field");*           
                    } else { 
                        $birthDate = clean_data($_POST["birthDate"]);
                    }
                    if (empty($_POST["languageType"])) {
                        *throw new Exception ("Please select a language");*                 
                    } else { 
                        $languageType = clean_data($_POST["languageType"]);
                    }
                    if (empty($_POST["interest"])) {
                        *throw new Exception ("Please select a interest");*             
                    } else { 
                        $interest = clean_data($_POST["interest"]);
                    }

                    $stmt->bindParam(':firstName', $firstName);
                    $stmt->bindParam(':lastName', $lastName);
                    $stmt->bindParam(':idNumber', $idNumber);
                    $stmt->bindParam(':mobileNumber', $mobileNumber);
                    $stmt->bindParam(':email', $email);
                    $stmt->bindParam(':birthDate', $birthDate);
                    $stmt->bindParam(':languageType', $languageType);
                    $stmt->bindParam(':interest', $interest);

                    $created = date('Y-m-d H:i:s');
                    $stmt->bindParam(':created', $created);

                    if($stmt->execute()){
                        echo "<div class='alert alert-success'>Member was saved.</div>";
                    } else {
                        echo "<div class='alert alert-danger'>Unable to save this member.</div>";
                    }
                }

                catch(Exception $exception){
                    *echo '<h4 style="color:red;">' . $exception->getMessage() . '</h4>';*
                }

在html中,我刚刚添加了所需的属性,如下所示:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
            <table class='table table-hover table-responsive table-bordered'>
                <tr>
                    <td>First Name: *</td>
                    <td><input type='text' name='firstName' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Last Name: *</td>
                    <td><input type='text' name='lastName' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>ID Number: *</td>
                    <td><input type='text' name='idNumber' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Mobile Number: *</td>
                    <td><input type='text' name='mobileNumber' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Email: *</td>
                    <td><input type='text' name='email' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Birth Date: *</td>
                    <td><input type='date' name='birthDate' class='form-control' required/></td>
                </tr>
                <tr>
                    <td>Language: *</td>
                    <td>

                        <select class="form-control" name="languageType" required>

                          <option>Select One...</option>
                          <option>Afrikaans</option>
                          <option>English</option>
                          <option>Zulu</option>
                          <option>Xhosa</option>
                          <option>Venda</option>
                          <option>French</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td>Interest: *</td>
                    <td>

                        <select class="form-control" name="interest" required>

                          <option>Select One...</option>
                          <option>Golf</option>
                          <option>Rugby</option>
                          <option>Tennis</option>
                          <option>Cricket</option>
                          <option>Swimming</option>
                          <option>Hiking</option>
                          <option>Surfing</option>
                          <option>Movies</option>
                          <option>Swords</option>

                        </select>
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <input type='submit' name='submit' value='Save' class='btn btn-primary' />
                        <a href='index.php' class='btn btn-danger'>Back to view members</a>
                    </td>
                </tr>
            </table>
        </form>

答案 5 :(得分:-1)

你错过了回报。在您的代码中,您有

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailError = "Please enter a valid email address";
}

这只会将您的消息分配给变量,但仍会继续保存。试试这样的事情

$sErrors = '';    
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $sErrors  .= "Please enter a valid email address \n";
    }
if (empty($_POST["mobileNumber"])) {
            $sErrors  .= "Mobile Nr is Required Please\n";                
        }

if (strlen($sErrors) > 0) {
    return $sErrors;
}

当然,您必须在所有if if validator

中执行此操作