1

I have been given this code where I am asked to add validation function using Javascript. It is a sign up form whereupon submit, it should validate it by alerting a pop up message to the user if the First name, Last name, Username, or password is empty or if the password's character length is less than 8 characters. and if once the conditions are met, it will pop up a message that tells the user that the sign up is a success

<?php
    require "function.php";

    if($_SERVER['REQUEST_METHOD'] == "POST")
    {
        $username = addslashes($_POST['username']);
        $password = addslashes($_POST['password']);
        $date = date('Y-m-d H:i:s');
        $firstname = ($_POST['firstname']);
        $lastname = ($_POST['lastname']);


        $query = "insert into users (username,password,date,firstname,lastname) 
        values ('$username','$password','$date','$firstname','$lastname')";

        $result = mysqli_query($con,$query);

        header("Location: login.php");
        die;
    }
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="LogIn.css">
    
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    <title>Sign up</title>
</head>
<body>
    <nav> 
        <ul>
            <li><a href="home.php">Home</a></li>

            <a href="login.php"><button class = "button2"> <span class = "sign"> Login </button></a>
            <a href="signup.php"><button class = "button2"> <span class="sign"> Sign Up</span></button></a>
        </ul>
    </nav>
    
    <div class="signup"> 
        <div class="signup-box">
            <h2>Sign Up for Free</h2>
            <p>It's quick and easy</p>
            
            <form method="post" id = "form">
                <div class ="box">
                    <i class="material-icons">person</i>
                    <input type = "text" name = "firstname" placeholder = "First Name" id = "First_name" required>
                </div>
            
                <div class = "box">
                    <i class="material-icons">person</i>
                    <input type = "text" name = "lastname" placeholder = "Last Name" id = "Last_Name" required>
                </div>
            
                <div class="box">
                    <i class="material-icons">account_circle</i>
                    <input type="text" name="username" placeholder="Your username" id = "User_name" required>
                </div>
            
                <div class="box">
                    <i class="material-icons">lock</i>
                    <input type="password" name="password" placeholder="Your Password" id = "Password" required>
                </div>

                <input type="submit" id = "submit" value="Sign Up"></input>
           
            </form>

        </div>
    </div>
</body>
</html>

I have tried using If statements and comparing each fields value to null and for the password, and I compared the password field's value length if it is less than 8. But it doesn't work and whenever I click on submit

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Reign0004
  • 13
  • 2
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. `addslashes` does not help you at all here. – ADyson Nov 18 '22 at 16:11
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Nov 18 '22 at 16:11
  • Also, please don't store passwords in plain text - that is another security risk. Learn about [password hashing](https://www.php.net/manual/en/faq.passwords.php) instead. See also [How to use PHP's password_hash to hash and verify passwords](https://stackoverflow.com/questions/30279321/how-to-use-phps-password-hash-to-hash-and-verify-passwords) – ADyson Nov 18 '22 at 16:11

1 Answers1

0

In your form tag you will need to specify an onsubmit event, like

onsubmit="return validateForm();"

So, if your validateForm function returns true ("valid"), then the form is submitted and if it returns false, then the form is not submitted. Now, let's implement validateForm:

function validateForm() {
    let firstName = document.getElementById("First_name").value;
    let lastName = document.getElementById("Last_Name").value;
    let username = document.getElementById("User_name").value;
    let password = document.getElementById("Password").value;

    error = "";

    let isValid = (!!firstName);

    if (!isValid) error = "First name is empty";

    isValid = isValid && lastName;

    if ((!isValid) && (!error)) error = "Last name is empty";
    
    isValid = isValid && username;

    if ((!isValid) && (!error)) error = "Username is empty";

    isValid = isValid && password;

    if ((!isValid) && (!error)) error = "Password is empty";

    isValid = isValid && (password.length >= 8);

    if ((!isValid) && (!error)) error = "Password too short";

    if (isValid) alert("Validation succeeded");
    else alert(error);

    return isValid;
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • is there a way where the alert message are unique for each field? for example "password must not be less than 8 characters" instead of "Validation failed" – Reign0004 Nov 18 '22 at 16:52
  • @Reign0004 edited my answer to provide more meaningful error messages. Please take a look. If it solves your problem, then you may consider accepting it as the correct answer. – Lajos Arpad Nov 18 '22 at 17:08
  • I tried your answer and it worked, Thank you. – Reign0004 Nov 18 '22 at 19:29