Francesco Chiari
Francesco Chiari

Reputation: 39

How to display validation errors in my website?

I just want this PHP code to display form validation errors in my website whenever someone uses the form incorrectly. Here is the code and I will also include the HTML of the form.

The code is only for reference, if you have a better way of doing it, then please show me.

<?php

if (isset($_POST['submit'])) {

    include_once 'dbh.inc.php';

    $first = mysqli_real_escape_string($conn, $_POST['first']);
    $last = mysqli_real_escape_string($conn, $_POST['last']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $number = mysqli_real_escape_string($conn, $_POST['number']);
    $uid = mysqli_real_escape_string($conn, $_POST['uid']);
    $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);

    // Error handlers
    // Check for empty fields

    if (empty($first) || empty($last) || empty($email) || empty($number) || empty($uid) || empty($pwd)) {
        header("Location: ../signup.php?signup=empty");
        exit(); 
    } else {
        // Check if input characters are valid
        if (!preg_match("/^[a-zA-Z'-]+$/",$first) || !preg_match("/^[a-zA-Z'-]+$/",$last)) {
            header("Location: ../signup.php?signup=invalid");
            exit(); 
        } else {
            // Check if email is valid
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                header("Location: ../signup.php?signup=invalidemail");
                exit(); 
            } else {
                if (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $number)) {
                    header("Location: ../signup.php?signup=invalidnumber");
                    exit();
            } else {
                $sql = "SELECT * FROM users WHERE user_uid='$uid'";
                $result = mysqli_query($conn, $sql);
                $resultcheck = mysqli_num_rows($result);

                if ($resultcheck > 0) {
                    header("Location: ../signup.php?signup=usertaken");
                    exit(); 
                } else {
                   // Hashing the password
                    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
                   // Insert the user into the database
                    $sql = "INSERT INTO users (user_first, user_last, user_email, user_number, user_uid, user_pwd) VALUES ('$first', '$last', '$email', '$number', '$uid', '$hashedPwd');";
                    mysqli_query($conn, $sql);
                    header("Location: ../accountcreated.php");
                    exit(); 

                }
            }
        }
    }

} else {
    header("Location: ../signup.php");
    exit();
}

Here is the HTML code:

<form class="memberform" action="includes/signup.inc.php" method="POST" novalidate>

                <input id="spfirst" class="form_fname" type="text" name="first" placeholder="First Name">
                <span class="error_form"></span>

                <input id="splast" class="form_lname" type="text" name="last" placeholder="Last Name">
                <span class="error_form"></span>

                <input class="form_email" type="email" name="email" placeholder="E-mail">
                <span class="error_form"></span>

                <input id="spnumber" class="form_tel" type="tel" name="number" placeholder="Phone number">
                <span class="error_form"></span>

                <input id="spuser" class="form_user" type="text" name="uid" placeholder="Username">
                <span class="error_form"></span>

                <input class="form_password" type="password" name="pwd" placeholder="Password">
                <span class="error_form"></span>

                <button type="submit" name="submit">Create Account</button>

                  </form>

Okay there it is. I already tried so many things a nothing seems to work... Maybe it's due to my limited knowledge with PHP.

Upvotes: 1

Views: 183

Answers (2)

Shahlin Ibrahim
Shahlin Ibrahim

Reputation: 1095

Since you're redirecting users to the signup page with a specific error message (Example: usertaken), you can use $_GET to handle the errors.

So in your signup page, do this

$error should = "" ;
if(isset($_GET['signup'])) {
    $error = $_GET['signup'];
    if(!empty($error){
        //check for specific errors
        if($error == "usertaken"){
             $errorMsg = "The username has already been taken, try again";
        } 
    } 
}

You can use the $errorMsg in your HTML and put it where you want to display the error and design it accordingly.

NOTE: I have not done any sanitization, trying to keep this short.

Upvotes: 0

Zeke
Zeke

Reputation: 1291

This is not the best way to do it in my opinion, but following your current code, I suggest you do this.

In your signup.php file, add this where you want the error message to appear (within the HTML if you want):

<?php
if(isset($_GET['signup'])){
    switch($_GET['signup']){
        case 'empty':
            $msg = 'Empty fields';
            break;
        case 'invalid':
            $msg = 'Invalid input';
            break;
        case 'invalidemail':
            $msg = 'Invalid email';
            break;
        case 'invalidnumber':
            $msg = 'Invalid number';
            break;
        case 'usertaken':
            $msg = 'User taken';
            break;
        default:
            $msg = ''; // Default message, if any
            break;
    }
    echo '<div class="error_div">'.$msg.'</div>'; // here's where the message appears
}
?>

That will show your messages. Obviously, feel free to change the class name and style it as you wish.

Or you can simply do something like this (changing the text and stuff depending on the result you're looking for):

<?php
if(isset($_GET['signup'])){
    if($_GET['signup'] == 'empty'){
        echo '<span class="error_form">Empty values</span>';
    }
}
?>

Upvotes: 2

Related Questions