PHP Contact Form: all field errors execute but need to execute individually

I have a PHP contact form, and I would like to validate every field individually when the user clicks the submit btn each time, but at the moment it displays all validation errors for all fields

Currently I have the following: http://pastebin.com/S29C0axL

Any help to change the if/else statements?

Im lost…

Your first “if” doesn’t stop the checking of the rest of the form.

^^^ That is true

What you can do is this…

[php]// check each field
if (trim($_POST[‘name’]) === “”) {
// if this evaluates to true it will stop processing
}
// $_POST[‘name’] has a value, let’s continue
else if (trim($_POST[‘email’]) === “”) {
// if this evaluates to true it will stop processing
}
[/php]

What I would do is have a bunch of validating functions to validate the form and then have the if-else statements correspond to those functions.

Here’s a registration form that I did that uses the same principles.

The validating function(s) in validate.php :
[php]<?php

function check_for_content(array $data, $password) {
/* Making sure all input fields are entered */
if (empty($data[‘username’]) || empty($password) || empty($data[‘first_name’]) || empty($data[‘last_name’]) || empty($data[‘emailAddress’])) {
return ‘fail’;
} else {
return ‘success’;
}
}

/* Check database table to see if username is already taken /
function check_for_duplicates($username, $pdo) {
try {
/
Setup up the query, it doesn’t matter if nothing is selected, for
we are just trying to see if the username is in the database table.
Execute a prepared statement by passing an array of values */
$query = “SELECT 1 FROM " . DATABASE_TABLE . " WHERE username = :username”;

$stmt = $pdo->prepare($query);

$stmt->bindParam(':username', $username);

$stmt->execute();

/* The fetch() method returns an array representing the "next" row from 
  the selected results, or false if there are no more rows to fetch. */
$row = $stmt->fetch();
/* If a row was returned, then we know a matching username was found in
  the database already and we should return a true value back. */
if ($row) {
  return 'fail';
} else {
  return 'success';
}

} catch (PDOException $e) { // Report the Error!
echo “DataBase Error: Could not check username against database table.
” . $e->getMessage();
} catch (Exception $e) {
echo “General Error: Username could not be checked for some general reason.
” . $e->getMessage();
}
} // End of check_for_duplicates function:

/* Validate the password /
function check_password($password) {
/
Using Regex to check password /
if (!preg_match_all(’$\S
(?=\S{8,})(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])(?=\S*[\W])\S*$’, $password)) {
$status = ‘fail’;
} else {
$status = ‘success’;
}
return $status;
}

/* Verify that passwords entered match */
function verify_password($password, $verify) {
if ($password != $verify) {
return ‘fail’;
} else {
return ‘success’;
}
}

/* Validate the email address /
function validate_email_address($email) {
/
Check to see if user has entered a valid email address */
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return ‘success’;
} else {
return ‘fail’;
}
}

/* Save to MySQL Database Table /
function saveToMySQL($pdo, array $data, $password, $confirmation_code) {
/
Hash the Password with password_hash (PHP 5.5 or greater) /
/
PHP 5.3, 5.4 - https://github.com/ircmaxell/password_compat/blob/master/lib/password.php /
$password_hash = password_hash($password, PASSWORD_BCRYPT, array(“cost” => 15));
try {
/
Set the query with the user’s profile using prepared statements /
$query = ‘INSERT INTO ’ . DATABASE_TABLE . ’ ( username, password, confirmation_code, first_name, last_name, email, date_added ) VALUES ( :username, :password, :confirmation_code, :first_name, :last_name, :email, NOW() )’;
/
Prepare the statement using PDO prepare method /
$stmt = $pdo->prepare($query);
/
Execute statement along with the prepared values /
$result = $stmt->execute([’:username’ => $data[‘username’], ‘:confirmation_code’ => $confirmation_code ,’:password’ => $password_hash, ‘:first_name’ => $data[‘first_name’], ‘:last_name’ => $data[‘last_name’], ‘:email’ => $data[‘emailAddress’] ]);
/
If a result is return back then return “success” back */
if ($result) {
unset($_SESSION[‘username’]);
unset($_SESSION[‘first_name’]);
unset($_SESSION[‘last_name’]);
unset($_SESSION[‘emailAddress’]);
unset($_SESSION);
header(‘Location: newUser.php’);
exit();
} else {

}  

} catch (PDOException $e) { // Report the Error!
echo “DataBase Error: The user could not be added.
” . $e->getMessage();
} catch (Exception $e) {
echo “General Error: The user could not be added.
” . $e->getMessage();
}
}
[/php]

and the top php portion of my registration page :
[php]$check = FALSE;
$message = [];
$submit = filter_input(INPUT_POST, ‘action’, FILTER_SANITIZE_SPECIAL_CHARS);

if (isset($submit) && $submit === ‘register’) {
/* Get the Variables from the input tags */
$_SESSION[‘username’] = filter_input(INPUT_POST, ‘username’, FILTER_SANITIZE_SPECIAL_CHARS);
$password = filter_input(INPUT_POST, ‘password’, FILTER_SANITIZE_SPECIAL_CHARS);
$verify = filter_input(INPUT_POST, ‘verify’, FILTER_SANITIZE_SPECIAL_CHARS);
$_SESSION[‘first_name’] = filter_input(INPUT_POST, ‘first_name’, FILTER_SANITIZE_SPECIAL_CHARS);
$_SESSION[‘last_name’] = filter_input(INPUT_POST, ‘last_name’, FILTER_SANITIZE_SPECIAL_CHARS);
$_SESSION[‘emailAddress’] = filter_input(INPUT_POST, ‘emailAddress’, FILTER_SANITIZE_SPECIAL_CHARS);

/* Make sure the user can’t add spaces to bypass the registeration form */
$_SESSION[‘username’] = isset($_SESSION[‘username’]) ? trim($_SESSION[‘username’]) : ‘’;
$_SESSION[‘first_name’] = isset($_SESSION[‘first_name’]) ? trim($_SESSION[‘first_name’]) : ‘’;
$_SESSION[‘last_name’] = isset($_SESSION[‘last_name’]) ? trim($_SESSION[‘last_name’]) : ‘’;
$_SESSION[‘emailAddress’] = isset($_SESSION[‘emailAddress’]) ? trim($_SESSION[‘emailAddress’]) : ‘’;

/* Validation checks done on the server-side */
$check_content = check_for_content($_SESSION, $password);
if ($check_content === ‘fail’) {
$message[‘empty’] = “red”;
$check = TRUE;
} else {
$message[‘empty’] = “”;
}

/* Check to see if password and verify matches */
$verify_password = verify_password($password, $verify);

if ($verify_password === ‘fail’) {
$message[‘mismatch’] = “red”;
$check = TRUE;
} else {
$message[‘mismatch’] = “”;
}

/* Check the password */
$check_password = check_password($password);

if ($check_password === ‘fail’) {
$message[‘invalid’] = ‘red’;
$check = TRUE;
} else {
$message[‘invalid’] = “”;
}

/* Validate the email address */
$check_email = validate_email_address($_SESSION[‘emailAddress’]);

if ($check_email === ‘fail’) {
$message[‘invalidEmail’] = “red”;
$check = TRUE;
} else {
$message[‘invalidEmail’] = “”;
}

/* Check to see if username is available */
$check_duplicate = check_for_duplicates($_SESSION[‘username’], $pdo);

if ($check_duplicate === ‘fail’) {
$message[‘duplicate’] = “red”;
$check = TRUE;
} else {
$message[‘duplicate’] = “”;
}

/* If everything checks out OK insert data into the database table */
if (!$check) { // Not true = FALSE

$send = new SendConfirmation($_SESSION);  // Setup PHPMailer:
$resultCode = $send->sendEmailVerification(); // Send confirmation_code to user's email address:
if ($resultCode) { 
  /* Save to database table if result code is true */
  saveToMySQL($pdo, $_SESSION, $password, $resultCode);
}

}

}[/php]

Note I just have the word red in the error message that is a css class that highlights the requirement in red notifying the user that it needs correction. I find doing it this way simplifies the logic, well at least it does for me. ;D HTH ~ John

Sponsor our Newsletter | Privacy Policy | Terms of Service