Home > Software design >  How can I repeat JavaScript form validation until all inputs are correct, then insert the inputs in
How can I repeat JavaScript form validation until all inputs are correct, then insert the inputs in

Time:10-31

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. 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
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; [email protected]</b>
        </div>
        <div class="copyRight">Copyright &copy; 2021 YummyDonations </div>         
    </div>
</footer>
</body> 
</html>

And This is the JavaScript validation function:

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; 
        }
    }
}

CodePudding user response:

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. 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. 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. 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; [email protected]</b>

    </div>
    <div class="copyRight">Copyright &copy; 2021 YummyDonations </div>
  </div>
</footer>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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.

  • Related