Adding Validation

Next, we need to put the two together: add the validation rules to our form and validate the form submission. This step works by sandwiching the validation rules and function call into the PHP at the top, to prevent the ft_api_process_form() function automatically redirecting when the form is submitted.

Note that we've also added in some PHP into the form itself. That code will automatically re-enter the form submission values that have been already entered. N.B. the "@" character that appears before the variables may look unfamiliar. All it does is suppress PHP warnings / notices that usually show up if the variable isn't already defined; e.g. on the first time the user loads the page.

<?php
require_once("path/to/form_tools/global/api/api.php");
$fields = ft_api_init_form_page("X"); // X would be your form ID

// validation time!
$errors = array();
if (isset($_POST['sbmt']))
{
  $rules = array();
  $rules[] = "required,subject,Please select a subject.";
  $rules[] = "required,fullname,Please enter your name.";
  $rules[] = "required,email,Please enter your email address.";
  $rules[] = "valid_email,email,Please enter a valid email address.";
  $rules[] = "required,comments,Please enter your comments.";
  $errors = validate_fields($_POST, $rules);

  // no errors - great! Now we process the page. The ft_api_process_form does
  // the job of both updating the database and redirecting to the next page
  if (empty($errors))
  {
    $params = array(
      "submit_button" => "sbmt",
      "next_page" => "thanks.php",
      "form_data" => $_POST,
      "finalize" => true
    );
    ft_api_process_form($params);
  }
  // it failed validation. Update $fields with the latest contents of the form data
  else
  {
    $fields = array_merge($_SESSION["form_tools_form"], $_POST);
  }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Sample Form</title>
</head>
<body>

<form method="post" action="<?=$_SERVER["PHP_SELF"]?>">

Subject: <select name="subject">
	<option value=""
	<?php if (@$fields["subject"] == "") echo "selected"; ?>>Please Select</option>
	<option value="General Comment"
	<?php if (@$fields["subject"] == "General Comment") echo "selected"; ?>>General Comment</option>
	<option value="Bug Report"
	<?php if (@$fields["subject"] == "Bug Report") echo "selected"; ?>>Bug Report</option>
	<option value="Feature Suggestion"
	<?php if (@$fields["subject"] == "Feature Suggestion") echo "selected"; ?>>Feature Suggestion</option>
</select><br />
Name: <input type="text" name="fullname" value="<?=htmlspecialchars(@$fields["fullname"])?>" /><br />
Email: <input type="text" name="email" value="<?=htmlspecialchars(@$fields["email"])?>" /><br />
Comments: <textarea name="comments"><?=@$comments?></textarea>

<input type="submit" name="sbmt" value="Submit Form" />

</form>

</body>
</html>
Edit Page