Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何用PHP和HTML验证表单?_Javascript_Php_Html_Validation - Fatal编程技术网

Javascript 如何用PHP和HTML验证表单?

Javascript 如何用PHP和HTML验证表单?,javascript,php,html,validation,Javascript,Php,Html,Validation,我目前正在参加一个网络开发课程的一个项目,我必须为营销产品创建一个注册页面,并将用户详细信息添加到数据库中。我已经有了基本的代码,但是在和我的老师交谈之后,我需要在网站上添加一些形式的数据验证。我曾尝试按照HTML5中的要求标记输入字段,并使用单独的JavaScript验证器,但如果我提交表单,我的PHP脚本过程中没有验证数据,则没有任何效果 我的目标是直接在表单上验证数据,以便错误消息显示在表单上,而不是显示在单独的页面上。目前,我在PHP代码中进行了一次检查,以查询数据库中已有的电子邮件,并

我目前正在参加一个网络开发课程的一个项目,我必须为营销产品创建一个注册页面,并将用户详细信息添加到数据库中。我已经有了基本的代码,但是在和我的老师交谈之后,我需要在网站上添加一些形式的数据验证。我曾尝试按照HTML5中的要求标记输入字段,并使用单独的JavaScript验证器,但如果我提交表单,我的PHP脚本过程中没有验证数据,则没有任何效果

我的目标是直接在表单上验证数据,以便错误消息显示在表单上,而不是显示在单独的页面上。目前,我在PHP代码中进行了一次检查,以查询数据库中已有的电子邮件,并终止脚本并回显错误,但它会在另一个页面上执行此操作

下面是到目前为止我已经准备好JavaScript验证器的代码。我还在学习PHP和HTML,所以我不知道还能尝试什么。有人能帮忙吗

HTML代码

<!DOCTYPE HTML>
<html>
<head>
        <title>Registration</title>
        <script src="scripts/gen_validatorv4.js" type="text/javascript"></script>
</head>
<body>
    <div id="register">
        <fieldset style="width:30%"><legend>Registration Form</legend> <!-- Give the table a width of 30% and a title of Registration Form -->
            <table border="0"> <!-- Add border to table -->
            <tr>
            <form method="POST" action="registration.php" id="register"> <!-- Use POST to submit form data to registration.php -->
                <td>First Name</td><td> <input type="text" name="firstname" ></td> <!-- Input field for First Name -->
                </tr>
                <tr>
                <td>Last Name</td><td> <input type="text" name="lastname" ></td> <!-- Input field for Last Name -->
                </tr>
                <tr>
                <td>Address 1</td><td> <input type="text" name="address1" ></td> <!-- Input field for Address 1 -->
                </tr>
                <tr>
                <td>Address 2</td><td> <input type="text" name="address2"></td> <!-- Input field for Address 2 -->
                </tr>
                <tr>
                <td>City</td><td> <input type="text" name="city" ></td> <!-- Input field for City -->
                </tr>
                <tr>
                <td>State</td><td> <input type="text" name="state" ></td> <!-- Input field for State -->
                </tr>
                <tr>
                <td>Zip Code</td><td> <input type="text" name="zipcode" ></td> <!-- Input field for Zip Code -->
                </tr>
                <tr>
                <td>Phone Number</td><td> <input type="text" name="phonenumber" ></td> <!-- Input field for Phone Number -->
                </tr>
                <tr>
                <td>Email</td><td> <input type="text" name="email" ></td> <!-- Input field for Email -->
                </tr> 
                <tr>
                <td>Sign up to marketing emails?</td><td> <input type="radio" name="marketingaccept" value="yes"></td> <!-- Radio button to be checked if user wants to sign up for marketing emails -->
                </tr>
                <td><input id="button" type="submit" name="submit" value="Register"></td> <!-- Submit button -->
            </form>
            <script type="text/javascript">
            var frmvalidator  = new Validator("register");
            frmvalidator.EnableOnPageErrorDisplay();
            frmvalidator.EnableMsgsTogether();
            frmvalidator.addValidation("firstname","req","Please provide your first name");

            frmvalidator.addValidation("email","req","Please provide your email address");

            frmvalidator.addValidation("email","email","Please provide a valid email address");

            frmvalidator.addValidation("lastname","req","Please provide your last name");

            frmvalidator.addValidation("address","req","Please provide your address");
            </script>
            </tr>
            </table>
        </fieldset>
    </div>
</body>
</html>
<?php

define('DB_HOST', 'localhost'); // Define database host
define('DB_NAME', 'andrewha_fhsuproject1'); // Define database name
define('DB_USER','*******'); // Define database username
define('DB_PASSWORD','********'); // Define database password

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to host or present an error if connection fails
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to database or present an error if connection fails


function newregister() // Create function newregister()
{
    $firstname = trim($_POST['firstname']); // Grab data from the first name field and trim excess white space
    $lastname = trim($_POST['lastname']); // Grab data from the last name field and trim excess white space
    $address1 = trim($_POST['address1']); // Grab data from the address1 name field and trim excess white space
    $address2 = trim($_POST['address2']); // Grab data from the address2 name field and trim excess white space
    $city = trim($_POST['city']); // Grab data from the city field and trim excess white space
    $state = trim($_POST['state']); // Grab data from the state field and trim excess white space
    $zipcode = trim($_POST['zipcode']); // Grab data from the zipcode field and trim excess white space
    $phonenumber = trim($_POST['phonenumber']); // Grab data from the phonenumber field and trim excess white space
    $email = trim($_POST['email']); // Grab data from the email field and trim excess white space
    $marketingaccept =  $_POST['marketingaccept']; // Check to see whether the marketingaccept radio button is checked

    $sql="SELECT email FROM RegisteredUsers WHERE email='".$email."'"; // Look through existing emails to prevent duplication
    $resul=mysql_query($sql); // Perform above query
    $num = mysql_num_rows($resul); // Check above query to see if any rows match
    if ($num !=0){ // If a match is found...
        die("Sorry, you can only register once!.");  // ...the script is killed and an error is presented.
}   else // If no match is found, the script continues.
        $query = "INSERT INTO RegisteredUsers (firstname,lastname,address1,address2,city,state,zipcode,phonenumber,email,marketingaccept) VALUES ('$firstname','$lastname','$address1','$address2','$city','$state','$zipcode','$phonenumber','$email','$marketingaccept')"; // Create variable to insert  Grabbed data to database table and corresponding columns
        $data = mysql_query ($query)or die(mysql_error()); // Run above query or kill the script if an error is presented
    if($data) // Verify $data was run
    {
    header('Location: thankyou.html'); // Redirect to thankyou.html
    exit(); // End script
    }
}


if(isset($_POST['submit'])) // Check to see if submit button was hit...
{
    newregister(); // ...and go to newregister()
}
?>

登记处
登记表
名字
姓
地址1
地址2
城市
陈述
邮政编码
电话号码
电子邮件
注册营销电子邮件?
var frmvalidator=新验证器(“寄存器”);
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation(“firstname”、“req”、“请提供您的名字”);
frmvalidator.addValidation(“电子邮件”、“请求”、“请提供您的电子邮件地址”);
frmvalidator.addValidation(“电子邮件”、“电子邮件”、“请提供有效的电子邮件地址”);
frmvalidator.addValidation(“lastname”、“req”、“请提供您的姓氏”);
frmvalidator.addValidation(“地址”、“请求”、“请提供您的地址”);
PHP代码

<!DOCTYPE HTML>
<html>
<head>
        <title>Registration</title>
        <script src="scripts/gen_validatorv4.js" type="text/javascript"></script>
</head>
<body>
    <div id="register">
        <fieldset style="width:30%"><legend>Registration Form</legend> <!-- Give the table a width of 30% and a title of Registration Form -->
            <table border="0"> <!-- Add border to table -->
            <tr>
            <form method="POST" action="registration.php" id="register"> <!-- Use POST to submit form data to registration.php -->
                <td>First Name</td><td> <input type="text" name="firstname" ></td> <!-- Input field for First Name -->
                </tr>
                <tr>
                <td>Last Name</td><td> <input type="text" name="lastname" ></td> <!-- Input field for Last Name -->
                </tr>
                <tr>
                <td>Address 1</td><td> <input type="text" name="address1" ></td> <!-- Input field for Address 1 -->
                </tr>
                <tr>
                <td>Address 2</td><td> <input type="text" name="address2"></td> <!-- Input field for Address 2 -->
                </tr>
                <tr>
                <td>City</td><td> <input type="text" name="city" ></td> <!-- Input field for City -->
                </tr>
                <tr>
                <td>State</td><td> <input type="text" name="state" ></td> <!-- Input field for State -->
                </tr>
                <tr>
                <td>Zip Code</td><td> <input type="text" name="zipcode" ></td> <!-- Input field for Zip Code -->
                </tr>
                <tr>
                <td>Phone Number</td><td> <input type="text" name="phonenumber" ></td> <!-- Input field for Phone Number -->
                </tr>
                <tr>
                <td>Email</td><td> <input type="text" name="email" ></td> <!-- Input field for Email -->
                </tr> 
                <tr>
                <td>Sign up to marketing emails?</td><td> <input type="radio" name="marketingaccept" value="yes"></td> <!-- Radio button to be checked if user wants to sign up for marketing emails -->
                </tr>
                <td><input id="button" type="submit" name="submit" value="Register"></td> <!-- Submit button -->
            </form>
            <script type="text/javascript">
            var frmvalidator  = new Validator("register");
            frmvalidator.EnableOnPageErrorDisplay();
            frmvalidator.EnableMsgsTogether();
            frmvalidator.addValidation("firstname","req","Please provide your first name");

            frmvalidator.addValidation("email","req","Please provide your email address");

            frmvalidator.addValidation("email","email","Please provide a valid email address");

            frmvalidator.addValidation("lastname","req","Please provide your last name");

            frmvalidator.addValidation("address","req","Please provide your address");
            </script>
            </tr>
            </table>
        </fieldset>
    </div>
</body>
</html>
<?php

define('DB_HOST', 'localhost'); // Define database host
define('DB_NAME', 'andrewha_fhsuproject1'); // Define database name
define('DB_USER','*******'); // Define database username
define('DB_PASSWORD','********'); // Define database password

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to host or present an error if connection fails
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error()); // Connect to database or present an error if connection fails


function newregister() // Create function newregister()
{
    $firstname = trim($_POST['firstname']); // Grab data from the first name field and trim excess white space
    $lastname = trim($_POST['lastname']); // Grab data from the last name field and trim excess white space
    $address1 = trim($_POST['address1']); // Grab data from the address1 name field and trim excess white space
    $address2 = trim($_POST['address2']); // Grab data from the address2 name field and trim excess white space
    $city = trim($_POST['city']); // Grab data from the city field and trim excess white space
    $state = trim($_POST['state']); // Grab data from the state field and trim excess white space
    $zipcode = trim($_POST['zipcode']); // Grab data from the zipcode field and trim excess white space
    $phonenumber = trim($_POST['phonenumber']); // Grab data from the phonenumber field and trim excess white space
    $email = trim($_POST['email']); // Grab data from the email field and trim excess white space
    $marketingaccept =  $_POST['marketingaccept']; // Check to see whether the marketingaccept radio button is checked

    $sql="SELECT email FROM RegisteredUsers WHERE email='".$email."'"; // Look through existing emails to prevent duplication
    $resul=mysql_query($sql); // Perform above query
    $num = mysql_num_rows($resul); // Check above query to see if any rows match
    if ($num !=0){ // If a match is found...
        die("Sorry, you can only register once!.");  // ...the script is killed and an error is presented.
}   else // If no match is found, the script continues.
        $query = "INSERT INTO RegisteredUsers (firstname,lastname,address1,address2,city,state,zipcode,phonenumber,email,marketingaccept) VALUES ('$firstname','$lastname','$address1','$address2','$city','$state','$zipcode','$phonenumber','$email','$marketingaccept')"; // Create variable to insert  Grabbed data to database table and corresponding columns
        $data = mysql_query ($query)or die(mysql_error()); // Run above query or kill the script if an error is presented
    if($data) // Verify $data was run
    {
    header('Location: thankyou.html'); // Redirect to thankyou.html
    exit(); // End script
    }
}


if(isset($_POST['submit'])) // Check to see if submit button was hit...
{
    newregister(); // ...and go to newregister()
}
?>

我不知道您是否低估或误解了验证结果,请原谅我在这里长篇大论

您在客户机上的验证正是如此-它只会验证客户机上是否满足某些条件。一旦数据被发送到服务器,而没有进行验证/清理,您就有可能被人篡改和破坏您的数据库,甚至更糟

例如,可以完全跳过客户端验证,只需在地址栏中输入一个地址,或通过一个假装是web浏览器向服务器发送数据的脚本

按照上面编写代码的方式,服务器将接收数据,并且可以通过单个输入框(相当容易)将其设计为删除数据库中的所有数据,或者等待服务器配置,这可能会破坏服务器

其他地方关于stackoverflow的文章应该有助于更详细地讨论这个问题。我只是做了一个快速搜索,找到了这个:阅读一些答案

现在。。。关于验证表单数据,我建议您使用jquery。它是一个javascript附加库(意味着它完全是用javascript编写的),但它是跨浏览器兼容的(在某些浏览器中javascript处理数据的方式存在差异,因此您的普通javascript可能在所有浏览器上都能工作,也可能不能在所有浏览器上工作。但是,用jquery编写的代码将在所有浏览器上都能工作)

验证表单数据的简单性可以通过添加

class=“必需”

输入到表单中的每个输入标记

然后,使用jquery,您可以执行如下操作

// e will contain input field names of input tags that require but are missing data
var e=new Array();
// Get all input boxes with class "required", check the data input
// if the input length is less than one character in length, it
// will add the id tag to the "e" array.
$("input.required").each(function(){
if( $(this).val().length<1 )
{
    e.push( $(this).prop("id") );
}
});

// If e array has more than zero elements, it means more than zero input
// input tags are missing data and thus an alert is shown
if( e.length>0 )
{
 alert( "The following data fields are missing data:\n"+e.join(", ") );
}
//e将包含需要但缺少数据的输入标记的输入字段名称
var e=新数组();
//获取类为“必需”的所有输入框,检查数据输入
//如果输入长度小于一个字符,则
//将id标记添加到“e”数组中。
$(“input.required”)。每个(函数(){
if($(this.val().length0)
{
警报(“以下数据字段缺少数据:\n”+e.join(“,”);
}

检查前端验证,并在php中检查变量是否已设置,是否为所需格式,然后处理内容这是javascript验证的最佳用途,您可以使用php框架进行快速开发,如基本框架。请使用包含前端验证的问题更新您的问题。您提到这并没有阻止表单提交,但我们唯一能提供帮助的方法是查看问题代码。您需要共享脚本/gen_validatorv4.js您不应该只使用Javascript进行验证。任何人都可以使用客户端数据进行操作,因此您也应该始终检查服务器端