Jquery验证表单提交无效字段并保存到数据库

时间:2018-03-21 17:06:43

标签: javascript jquery

我正在尝试使用jquery validate插件设置一些服务器端验证,但我遇到了问题,似乎无法找到我的代码有什么问题。使用它传递的表单并将数据保存到数据库,即使字段无效或缺失。来自html的前端客户端验证工作正常,但不是后端。这是JsFiddle: https://jsfiddle.net/y7fmb7m1/3/ PHP:

<?php
/**
 * Start the session.
 */
session_start();

/**
 * Include ircmaxell's password_compat library.
 */
require 'lib/password.php';

/**
 * Include our MySQL connection.
 */
require 'connect.php';


//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
if (isset($_POST['register'])) {
    $form = $_POST;
    $username = $form['username'];
    $password = $form['password'];
    $firstName = $form['firstName'];
    $lastName = $form['lastName'];
    $address = $form['address'];
    $email = $form['email'];
    $age = $form['age'];
    $phone = $form['phone'];
//Retrieve the field values from our registration form.
    $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
    $pass = !empty($_POST['password']) ? trim($_POST['password']) : null;

//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.

//Now, we need to check if the supplied username already exists.

//Construct the SQL statement and prepare it.
    $sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
    $stmt = $pdo->prepare($sql);

//Bind the provided username to our prepared statement.
    $stmt->bindValue(':username', $username);

//Execute.
    $stmt->execute();

//Fetch the row.
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
    if ($row['num'] > 0) {
        die('That username already exists!');
    }

//Hash the password as we do NOT want to store our passwords in plain text.
    $passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));

//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
    $sql = "INSERT INTO users (username, password, email, phone, address, first_name, last_name, age) 
VALUES (:username, :password,:email, :phone, :address, :first_name, :last_name, :age)";
    $stmt = $pdo->prepare($sql);

//Bind our variables.
    $stmt->bindValue(':username', $username);
    $stmt->bindValue(':password', $passwordHash);
    $stmt->bindValue(':email', $email);
    $stmt->bindValue(':phone', $phone);
    $stmt->bindValue(':address', $address);
    $stmt->bindValue(':first_name', $firstName);
    $stmt->bindValue(':last_name', $lastName);
    $stmt->bindValue(':age', $age);

//Execute the statement and insert the new account.
    $result = $stmt->execute();

//If the signup process is successful.
    if ($result) {
        echo 'Thank you for registering with our website.';
        header('Location: login.php');

    }

}

?>

Html:

<form id="registration">
            <fieldset>
                <legend class="extraPlace">Register</legend>
                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    <input class="form-control" id="username" name="username" type="text" placeholder="Username *"
                           maxlength="8" minlength="4" required>

                </div>

                <div class="input-group margin">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                    <input class="form-control" id="password" name="password" type="password" placeholder="Password *"
                           maxlength="15" minlength="8" required>

                    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                    <input class="form-control" id="confirmPass" name="confirmPass" type="password" placeholder="Confirm Password *" required>

                </div>

                <div class="input-group margin">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    <input class="form-control" id="firstName" name="firstName" type="text" placeholder="First Name *" required>

                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    <input class="form-control" id="lastName" name="lastName" type="text" placeholder="Last Name *" required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                    <input class="form-control" id="email" name="email" type="email" placeholder="Email *" required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-phone-alt"></i></span>
                    <input class="form-control" id="phone" name="phone" type="text" maxlength="10" placeholder="Phone Number *" required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
                    <input class="form-control" id="address" name="address" type="text" placeholder="Address *" required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                    <input class="form-control" id="age" name="age" type="number" placeholder="Age *" min="18" required>
                </div>

                <div class="checkbox alignLeftContent">
                    <label>
                        <input type="checkbox" name="agreement" id="agreement" value="1" > I have read and agree to the <a
                                href="https://www.un.org/Depts/ptd/terms-and-conditions-agreement">Terms and Conditions
                            *</a>
                    </label><br>
                    <label>
                        <input type="checkbox" name="gdpr" id="gdpr" value="1" > GDPR Agreement *
                    </label>
                    <div class="margin"><span>* &nbsp;&nbsp; Mandatory fields</span></div>
                </div>

                <input id="register_submit" class="btn btn-success " type="submit" name="register" value="Register">
            </fieldset>
        </form>

JS:

 $(document).ready(function () {
        $.validator.addMethod('strongPass', function(value, element){
                return this.optional(element) || value.length >= 8 && value.length <= 15;
        }, 'Your password must be between 8 and 15 characters');

        $('#registration').validate({
            rules: {
                firstName: {
                    required: true
                },

                lastName: {
                    required: true
                },

                age: {
                    required: true
                },

                address: {
                    required: true
                },

                email: {
                    required: true,
                    email: true
                },

                password: {
                    required: true,
                    strongPass: true
                },

                confirmPass: {
                    required: true,
                    equalTo: "#password"
                },

                username: {
                    alphanumeric: true,
                    length: {
                        minimum: 4,
                        maximum: 8
                    }

                },

                phone: {
                    required: true,
                    length: {
                        minimum: 10,
                        maximum: 10
                    }
                }

            },
            messages: {
                username: {
                    alphanumeric: "Cannot contain special symbols",
                    length: {
                        minimum: "At least 4 symbols required",
                        maximum: "No more than 8 symbols allowed"
                    }

                },
                firstName: "Please enter your firstname",
                lastName: "Please enter your lastname",
                age: "Please enter your age",
                phone: "Pleae enter your phone",
                address: "Please enter your address",
                password: {
                    required: "Please provide a password"
                },
                email:{
                    required: "Please enter an email address",
                    email: "Please enter a <i>valid email</i> address"
                }


            },

            submitHandler: function (form) {
                $(form).submit();

            }
        });
    })

0 个答案:

没有答案