Skip to content

Lesson 05: Custom Form Validation

Anthony Ogundipe edited this page Mar 25, 2014 · 2 revisions

We shall now take a look at custom form validation.

If you wish to learn how to do automatic validation, please click Automatic Form Validation.

login.tpl.php

<form id="loginForm" name="loginForm" method="post">
  <p>
    <label>E-mail (email)
      <input type="text" name="email" id="email"/>
    </label>
  </p>

    <p>
    <label>Password
      <input type="text" name="pass" id="pass"/>
    </label>
  </p>
  
  <p>
    <input type="submit" value="Login" />
  </p>
</form>

index.php

<?php 
function phpformapi_validate_loginForm($validation,$vars)  {

//loop through all the individual fields and values
foreach($vars as $field=>$value) {

//validate email
if($field=="email"&&empty($value)) {
phpformapi::postError($field,"Please enter your email address");
}

//to pass this validation, you must use home as password
if($field=="pass"&&empty($value)) {
phpformapi::postError($field,"Please enter your password");
}
else if($field=="pass"&&$value!="home") {
phpformapi::postError($field,"Your password is not correct");
}

}
return;
}


function phpformapi_submit_loginForm($values)  {
  print "<h2>My form was submitted!</h2><p>These are the values we got:</p>";
  echo "<pre>";
  print_r($values);
  echo "</pre>";
  echo "<a href='index2.php'>Click here to fill a fresh form.</a>";
  exit();
}


include "lib/phpformapi.php";
?>

<html>
<head>
<title>Validation</title>
<link rel="stylesheet" href="validation.css">
</head>
<body>
<?php
//in case there are form errors, display them nicely here
$errors=phpformapi::getErrors('loginForm');
if($errors) {
echo '<div class="error_box" style="display: block;">';
echo $errors;
echo '</div>';
}

echo phpformapi::get("login.tpl.php"); 
?>
</body>
</html>

Explanation: The validation routine is supplied with 2 parameters:

  • $validation -> contains field and validation rules (explained in the previous section)
  • $vars -> contains an array of field and values submitted by user
  • phpformapi::postError($field,$message) is the routine to display an error message, and also mark that field as having failed validation.

To learn more about validation, please download the zip master and check example10