简体   繁体   English

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

[英]How can I repeat JavaScript form validation until all inputs are correct, then insert the inputs in the database?

I am trying to create a sign up page and to validate the form I used JavaScript, but when I enter some invalid input in the form, the alert message show up and once I click "OK" it redirects me to the other page and inserts the input in the database.我正在尝试创建一个注册页面并验证我使用 JavaScript 的表单,但是当我在表单中输入一些无效的输入时,会显示警报消息,一旦我单击“确定”,它就会将我重定向到另一个页面并插入数据库中的输入。 So how can I block it from inserting the input unless it is validated and correct?那么如何阻止它插入输入,除非它被验证和正确?

This is my Signup page with PHP in it:这是我的带有 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" alt="logo" width="100" height="100">
            </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" alt="welcome" width="1535" height="700">
                <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>

And This is the JavaScript validation function:这是 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 = /^\d{12}$/;
        
        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; 
        }
    }
}

The first step in using a form submit callback like this would be to prevent the form submitting by intercepting the event and calling the preventDefault method.使用这样的表单提交回调的第一步是通过拦截event并调用preventDefault方法来阻止表单提交。 If the form's method was changed to GET even if the form was submitted the PHP would not process the request anyway so we can change the method once all logic tests have been performed on the content.如果表单的方法更改为 GET,即使表单已提交,PHP 也不会处理请求,因此我们可以在对内容执行所有逻辑测试后更改方法。 The submit event callback needs to return a boolean to indicate the success or failure of the validation - if you set a simple variable as true it's value can be changed if a test fails.提交事件回调需要返回一个布尔值来指示验证的成功或失败——如果你将一个简单的变量设置为 true,它的值可以在测试失败时更改。 That boolean variable will be returned to the event handler.该布尔变量将返回给事件处理程序。

 function validateFormRec(e){ e.preventDefault(); const form=document.forms.myForm; const col=[...form.elements]; const pttn=/^\\d{12}$/; 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" alt="logo" width="100" height="100"> </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" alt="welcome" width="1535" height="700"> <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>

Try to use:尝试使用:

function validateFormRec(){
    e.preventDefault();
    ...
}

At the beginning of your function validateFormRec() , to prevent the form from submitting in case it returns false .在函数validateFormRec()的开头,防止表单在返回false 时提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM