PHP验证仅验证表单中的第一个文本框

时间:2014-12-25 12:09:42

标签: javascript php forms validation pdo

当我提交表单时,它会执行所有内容,但当我在其他文本框中包含表单验证时,它不会听,只会检查usernameTxt文本框,就是这样。

我尝试过使用JavaScript,但我不知道如何使用JS进行验证,但使用PHP进行处理。

如果有人可以帮忙,请说出来!

这是我的代码:

<?php
//Used for stopping users seeing an errors only for our eyes.
//commented out when published
error_reporting(-1);
ini_set('display_errors', 'On');
include 'includes/dbconnect.php';
session_start();
$error = "";
$username = $_POST['usernameTxt'];
$password = sha1($_POST['passwordTxt']);
$cnfrmPass = sha1($_POST['cnfrmPasswordTxt']);
$email = $_POST['emailTxt'];
$cnfrmEmail = $_POST['cnfrmEmailTxt'];
$fName = $_POST['fNameTxt'];
$lName = $_POST['lNameTxt'];

try{
    if(isset($_POST['submitBn'])){
        if(!empty($username)){
            $query = dbConnect()->prepare("INSERT INTO usersInfo (Username, Password, Email, FirstName, LastName) VALUES (:username, :password, :email, :fName, :lName)");
            $query->bindParam(':username', $username);
            $query->bindParam(':password', $password);
            $query->bindParam(':email', $email);
            $query->bindParam(':fName', $fName);
            $query->bindParam(':lName', $lName);

            if($query->execute()){
                header('Location: signin.php');
            }else{
                $error = "ERROR!";
            }
        }else{
            $error = "Username cannot be empty!";
        }
    }else{
        $error = "<h3>Form cannot be empty!</h3>";
    }
}catch(PDOException $e){
        $error = $e->getMessage();
    }

?>
<?php
include 'includes/head.php';
include 'includes/header.php';
?>
<div class="wrapper style2" style="margin-top: 20px;">
    <article id="work">
        <header>
            <h2>Register Here.</h2>
            <h3><?php  echo $error; ?> </h3>
            <p>If you don't have an account why not <a href="register.php">register</a>?</p>
        </header>
        <div class="container">
            <div class="row">
                <div class="4u">
                    <section class="box style1">
                        <form name="regForm" action="register.php?attempt" method="post">
                            <label for="username" >Username</label>
                            <input type="text" name="usernameTxt" style="margin-top: 5px; margin-     bottom:5px;"/>
                            <label for="password" >Password</label>
                            <input type="password" name="passwordTxt" style="margin-top: 5px; margin-bottom:5px;"/>
                            <label for="cnfrmPass" >Password Confirm</label>
                            <input type="password" name="cnfrmPasswordTxt" style="margin-top: 5px; margin-bottom:5px;"/>
                            <label for="email" >Email</label>
                            <input type="email" name="emailTxt" style="margin-top: 5px; margin-bottom:5px;"/>
                            <label for="cnfrmEmail" >Confirm Email</label>
                            <input type="email" name="cnfrmEmailTxt" style="margin-top: 5px; margin-bottom:5px;"/>
                            <label for="fName" >First Name</label>
                            <input type="text" name="fNameTxt" style="margin-top: 5px; margin-bottom:5px;"/>
                            <label for="lName" >Last Name</label>
                            <input type="text" name="lNameTxt"  style="margin-top: 5px; margin-bottom:5px;"/>
                            <input type="submit" name="submitBn" style="margin-top: 5px; margin-bottom:5px;"/>
                        </form>
                    </section>
                </div>
            </div>
        </div>
    </article>
</div>
<?php   include 'includes/footer.php'; ?>

2 个答案:

答案 0 :(得分:0)

您需要使用检查行扩展PHP脚本。全部加起来。如果达到某个数字,则所有字段都是正确的,如果不是在不正确的字段上中止。这也可以在JavaScript中完成。将为您提供两种解决方案。

if ($_SERVER['REQUEST_METHOD'] == "POST") //only execute when a post is sent to register.php
{
    $username = $_POST['usernameTxt'];
    $password = sha1($_POST['passwordTxt']);
    $cnfrmPass = sha1($_POST['cnfrmPasswordTxt']);
    $email = $_POST['emailTxt'];
    $cnfrmEmail = $_POST['cnfrmEmailTxt'];
    $fName = $_POST['fNameTxt'];
    $lName = $_POST['lNameTxt'];    

    function validate()
    {
        global $username, $password, $cnfrmPass, $email, $cnfrmEmail;
        var index = 0;
        //start the check
        if (!empty($username) )
        {
            index++;
        }
        else
        {
            return "Username can't be empty";
        }
        if ( (!empty($password) && !empty($cnfrmPass) ) && $password === $cnfrmPass)
        {
            index++; //password and confirm password are not empty and equal to each other.
        }
        else
        {
            if (empty($password) || empty($cnfrmPass))
            {
                return "password can't be empty";
            }
            else
            {
                return "passwords do not match";
            }
        }
        if ( (!empty($email) && !empty($cnfrmEmail) ) && $email === $cnfrmEmail) //you also want to check if this is a correct e-mail 
        {
            index++; //email and email password are not empty and equal to each other.
        }
        else
        {
            if (empty($email) || empty($cnfrmEmail))
            {
                return "Email can't be empty";
            }
            else
            {
                return "emails do not match";
            }
        }

        return index;
    }

    $validated = validate();
    if (validated == 3)
    {
        //validation pans out --> continue.
        $query = dbConnect()->prepare("INSERT INTO usersInfo (Username, Password, Email, FirstName, LastName) VALUES (:username, :password, :email, :fName, :lName)");
        $query->bindParam(':username', $username);
        $query->bindParam(':password', $password);
        $query->bindParam(':email', $email);
        $query->bindParam(':fName', $fName);
        $query->bindParam(':lName', $lName);

        if($query->execute()){
            header('Location: signin.php');
        }else{
            $error = "ERROR!";
        }

    }
    else
    {
        $error = $validated;        
    }
}    

您还可以在此处阅读的输入上使用HTML5验证:http://www.the-art-of-web.com/html/html5-form-validation/

解决方案2 JavaScript

<script language="JavaScript">
function validateForm()
{
    var index = 0;
    function error(obj)
    {
        obj.className = "input_error";
        obj.setAttribute("validate", false);
        document.getElementsByTagName("h3")[0].innerHTML += obj.previousElementSibling.innerHTML + " can not be empty.<br/>";
        return false;
    }
    function good(obj)
    {
        index++;
        obj.className = "input_good";
        obj.setAttribute("validate", true);
    }

    document.getElementsByTagName("h3")[0].innerHTML = ""; //empty h3 tag with error info.
    var form = document.getElementsByName("regForm")[0].querySelectorAll("input"); //select all input elements from form
    //iterate them
    for (var i = 0; i < form.length; ++i)
    {
        //use swith to avoid infinite if and elsing
        switch (form[i].type) //check on type.
        {
            //remember all inputs have a label as previousElementSibling
            case 'text' :
                //normal text fields.
                //check if empty and contains normal characters (no !@#$), including all diacritics
                form[i].value.length > 0 ? good(form[i]) : error(form[i]);

            break;
            case 'password' :
                //password fields.
                //check if empty
                form[i].value.length > 0 ? good(form[i]) : error(form[i]);

                if (form[i].name == 'cnfrmPasswordTxt' && form[i].value.length > 0) //if password then check if matches other password
                {
                    if (form[i].value === form[i+1].value)
                    {
                        good(form[i]);
                    }
                    else
                    {
                        form[i].className = "input_error";
                        form[i].setAttribute("validate", false);
                        document.getElementsByTagName("h3")[0].innerHTML += "Passwords do not match<br/>"; //notify the user that the passwords do not match.
                    }
                }
            break;
            case 'email' :
                //email fields.
                //check if empty
                form[i].value.length > 0 ? good(form[i]) : error(form[i]);

                if (form[i].name == 'cnfrmEmailTxt' && form[i].value.length > 0) //if password then check if matches other password
                {
                    if (form[i].value === form[i+1].value)
                    {
                        good(form[i]);
                    }
                    else
                    {
                        form[i].className = "input_error";
                        form[i].setAttribute("validate", false);
                        document.getElementsByTagName("h3")[0].innerHTML += "Emails do not match<br/>"; //notify the user that the emails do not match.
                    }
                }
            break;                          
        }
    }

    if (index == 9)
    {
        document.getElementsByName("regForm")[0].submit(); //submit once validated.
    }
    else
    {
        return false;
    }
}
 </script>

更改提交按钮

<input type="button" name="submitBn" value="Submit" onclick="validateForm()" style="margin-top: 5px; margin-bottom:5px;"/>

添加此css

<style type="text/css">
    .input_error {
        border: 1px solid red;
    }

    .input_good {
        border: 1px solid lime;
    }

</style>

答案 1 :(得分:0)

好吧,所以最后我决定不添加Javascript,这似乎有点过分......我想也许只是让服务器验证它 - 也许它会带来更少的安全问题?

无论哪种方式,我都采取了解决方法:

//setting variables to use here
$error = "";
$username = $_POST['usernameTxt'];
$password = sha1($_POST['passwordTxt']);
$cnfrmPass = sha1($_POST['cnfrmPasswordTxt']);
$email = $_POST['emailTxt'];
$cnfrmEmail = $_POST['cnfrmEmailTxt'];

//checking for any empty values or incorrect values
if(empty($username) === true){
    $error = "Username cannot be empty";
}
if($password != $cnfrmPass){
    $error = "Passwords do not match";
}
if($email != $cnfrmEmail){
    $error = "Emails do not match";
}

//if no errors occur start the registration process
if(empty($error) === true){
    $selectQ = dbConnect()->prepare("SELECT `Username` FROM `usersInfo` WHERE `Username`=:username");
    //setting the variables to the query
    $selectQ->bindParam(":username", $username);
    $selectQ->execute(); //execute query

    $count = $selectQ->rowCount(); //see if the above query has found anyone
    if($count > 0){
        $error = "User already exists. Please try again.";   
    }else{
        //if no users found start the insert query
        $insertQ = dbConnect()->prepare("INSERT INTO usersInfo (Username, Password, Email) VALUES (:username, :password, :email)");
        //setting the variables to the query
        $insertQ->bindParam(':username', $username);
        $insertQ->bindParam(':password', $password);
        $insertQ->bindParam(':email', $email);

        if($insertQ->execute()){
            //if the insert query executed successfully redirect them
            //to the login in page.
            header('Location: signin.php');
        }else{
            //otherwise show this error.
            $error = "Query could not execute!";
        }
    }
}