如何重复 JavaScript 表单验证,直到所有输入都正确,然后将输入插入数据库?

Posted

技术标签:

【中文标题】如何重复 JavaScript 表单验证,直到所有输入都正确,然后将输入插入数据库?【英文标题】:How can I repeat JavaScript form validation until all inputs are correct, then insert the inputs in the database? 【发布时间】:2021-12-15 03:25:15 【问题描述】:

我正在尝试创建一个注册页面并验证我使用 javascript 的表单,但是当我在表单中输入一些无效输入时,会显示警报消息,并且一旦我单击“确定”,它就会将我重定向到另一个页面并将输入插入数据库。 那么,除非经过验证且正确,否则如何阻止它插入输入?

这是我的注册页面,其中包含 php

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "yummydonations";

$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);

if(!$con) 
    die("failed to connect!");


if($_SERVER['REQUEST_METHOD'] == "POST") 
    
    $RecipientName = $_POST['Name'];
    $Number = $_POST['Number'];
    $password = $_POST['Password'];

        
    if(!empty($RecipientName) && !empty($Number) && !empty($password) && !is_numeric($RecipientName))
    
        $Recipient_id = random_int(0, 500);
        //mysql_real_escape_string($Recipient_id);
        //mysql_real_escape_string($RecipientName);
        //mysql_real_escape_string($password);
        //mysql_real_escape_string($Number);
        $query = "insert into recipient 
                        (id,name,password,mobile) 
                values ('$Recipient_id','$RecipientName','$password','$Number')";
        mysqli_query($con, $query);
        header("location:RecpPH.php");
        die();
            
    else 
        echo "Please enter some valid information!";
    

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign Up</title>
    <link rel="stylesheet" href ="SStyle.css">
    <script src="JavaScript.js"></script>     
    <!-- onclick="validateFormRec(); return false;"-->
</head>
<body>
    <header>
        <div class="header"> 
            <div class="title">Yummy Donations</div>
                <img src="Images/Logo.png"   >
            </div>
            <div id="bar" >
                <ul> 
                    <li></li><li></li><li></li>
                    <li> <a href="MainHomeP.php" accesskey = "t">Home</a> </li>
                    <li>/</li>
                    <li> Sign Up </li>
                </ul> 
            </div>
            <div class="image">
                <img src="Images/RecPage.jpg"   >
                <div class="innPicture">
                    <h1> Join Us! </h1>
                </div>
            </div>
    </header>
<main>
<br>
<body>
    <div class="SignUp">
        <h2> Sign Up </h2>
        <form id ="demo" name="myForm" method="POST" onsubmit="return validateFormRec()">

            <div class="container">
                <label for="Name"><b>Name:</b></label>
                <input id="RecipientsName" type="text" placeholder="Enter Name" name="Name" required  value= "">
                <label for="Number"><b>Mobile Number:</b></label>
                <input id="Number" type="text" placeholder="ex: 966563929302" name="Number"  required value= "">

                <label for="Password"><b>Password:</b></label>
                <input id="Password" type="password" placeholder="Enter Password" name="Password"  required value= "">
    
                <button type="submit">Sign Up</button>
            </div>
        </form>
    </div> 
</body>
</main>
<footer>
    <div class="footer">
        <h4>YummyDonations </h4>
        <p class="discription">Please help us with spreading awareness <br> to stop food waste!</p>
        <div class="verticalLine"></div>
        <div class="footerLink">
            <h2><br> Connect With Us</h2>
            <b>&#128222; +966502233445 <br> </b>
            <b>&#128224; +966 11 483 0773</b> <br>
            <b>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &#128233; YummyDonations@gmail.com</b>
        </div>
        <div class="copyRight">Copyright &copy; 2021 YummyDonations </div>         
    </div>
</footer>
</body> 
</html>

这是 JavaScript 验证函数:

function validateFormRec()
    var n = document.forms["myForm"]["Name"].value;
    var e = document.forms["myForm"]["Number"].value;
    var p = document.forms["myForm"]["Password"].value;
 
    if (n == "" || e == "" || p == "" ) 
        alert("One or more fields are empty! ");
        return false;
    else
        //PhoneNum Validation//
        var phoneno = /^\d12$/;
        
        if( !(e.startsWith("966")))
            alert("The Number must start with 966");             
        else if(!(e.match(phoneno)))
            alert("The number must contain 12 digits");
         else 
            //location.replace("RecpPH.php"); // Rec Home Page
            return true; 
        
    

【问题讨论】:

良好的代码缩进将帮助我们阅读代码,更重要的是,它将帮助您调试代码Take a quick look at a coding standard 为您自己的利益。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。 注意:您的 HTML 中有 2 个 &lt;body&gt; 标记,这会导致问题 每页不能有 2 个正文元素 您的脚本对SQL Injection Attack 开放。即使是if you are escaping inputs, its not safe!,您也应该始终在MYSQLI_PDO API 中使用prepared parameterized statements,而不是将用户提供的值连接到查询中。永远不要相信任何用户输入! “那么我如何阻止它插入输入,除非它经过验证且正确无误?” 您还必须在 PHP 中验证它并拒绝任何无效输入。 Javascript 只是为了方便用户,PHP 脚本无论如何都接受一切。 PHP 中的表单处理基础知识。 【参考方案1】:

使用这样的表单提交回调的第一步是通过拦截event 并调用preventDefault 方法来阻止表单提交。如果表单的方法更改为 GET,即使表单已提交,PHP 也不会处理请求,因此我们可以在对内容执行所有逻辑测试后更改方法。提交事件回调需要返回一个布尔值来指示验证的成功或失败 - 如果您将一个简单变量设置为 true,则它的值可以在测试失败时更改。该布尔变量将返回给事件处理程序。

function validateFormRec(e)
  e.preventDefault();

  const form=document.forms.myForm;
  const col=[...form.elements];
  const pttn=/^\d12$/;

  let bValid=true;

  col.some(n=>
    if( n.nodeType==1 && n.value=='' && n.type!='submit' )
      alert( '"' + n.name + '" cannot be empty!');
      bValid=false;
      return true;
    
  );

  if( !pttn.test(form.Number.value) )
    alert("The number must contain 12 digits");
    bValid=false;
  

  if( !form.Number.value.startsWith("966") )
    alert("The Number must start with 966");
    bValid=false;
  

  if( form.Password.value.length < 5 )
    alert('That Password is too short!');
    bValid=false;
  

  form.method='POST';
  return bValid;
<header>
  <div class="header"> 
    <div class="title">Yummy Donations</div>
    <img src="Images/Logo.png"   >
  </div>
  <div id="bar" >
    <ul>
      <li><a href="MainHomeP.php" accesskey = "t">Home</a></li>
      <li>Sign Up</li>
    </ul> 
  </div>
  <div class="image">
    <img src="Images/RecPage.jpg"   >
    <div class="innPicture">
      <h1> Join Us! </h1>
    </div>
  </div>
</header>

<main>
  <br>
  <div class="SignUp">
    <h2> Sign Up </h2>
    <form name="myForm" onsubmit="return validateFormRec(event)">
      <div class="container">
        <label>
          <b>Name:</b>
          <input type="text" placeholder="Enter Name" name="Name" />
        </label>

        <label>
          <b>Mobile Number:</b>
          <input type="text" placeholder="ex: 966563929302" name="Number" />
        </label>

        <label>
          <b>Password:</b>
          <input type="password" placeholder="Enter Password" name="Password" />
        </label>

        <input type='submit' value='Sign up' />
      </div>
    </form>
  </div>
</main>
<footer>
  <div class="footer">
    <h4>YummyDonations </h4>
    <p class="discription">Please help us with spreading awareness <br> to stop food waste!</p>
    <div class="verticalLine"></div>

    <div class="footerLink">
      <h2><br> Connect With Us</h2>
      <b>&#128222; +966502233445 <br> </b>
      <b>&#128224; +966 11 483 0773</b> <br>
      <b>&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &#128233; YummyDonations@gmail.com</b>

    </div>
    <div class="copyRight">Copyright &copy; 2021 YummyDonations </div>
  </div>
</footer>

【讨论】:

以上是关于如何重复 JavaScript 表单验证,直到所有输入都正确,然后将输入插入数据库?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JavaScript 验证此表单上的邮政编码?

php通过token验证表单重复提交

一脸懵逼学习Struts数据校验,数据回显,模型驱动,防止表单重复提交。

javascript 如何获取表单中所有文本框

Javascript 表单验证器功能无法正常工作

如何使用表单验证防止重复提交