serverside form-validation with php

Television Tower "Fernsehturm" Berlin, by Christoph Burmeister (own photo)

Television Tower „Fernsehturm“ Berlin, by Christoph Burmeister (own photo)

Validating forms is (from my view) one of the most important things, developers have to do. Because in the beginning, lets say 30years ago, applications were written for developers by developers. If there was a form (or shell-input) which asks for a value with „DD/MM/YYYY“ no developer would insert „29th of February 89″… Actually users will do that. Meanwhile there are a bunch of developers writing applications for other developers AND users. So then input-validation became important because users do not think the way, developers do.

For my own thoughts to remember, a simple small validation (server-side, because not everybody is interested in using Javascript).

First you have a controller which has to handle the incoming requests:

   $step = ''; 	
   if (isset($_GET['step'])){ 		
      $step = $_GET['step']; 	
   } else{ 		
      $step = 1; 	

   switch ($step){ 		
      case '1': 			
         // hide the error-message 			
         $errorStyle = 'visibility:hidden'; 			
         include 'step1.php'; 			
      case '2': 			
         $value = $_POST['value']; 			
         if (!is_numeric($value)){ 				
            // show the error-message 				
            $errorStyle = 'color:red'; 				
            include 'step1.php'; 			
         } else { 				
            include 'step2.php'; 			

Then you have the first form where the user has to enter a value:

      <h1>step 1</h1>
      <form action="controller.php?step=2" method="POST">
         enter a number <input type="text" name="value" />
         <span style="<?php echo $errorStyle ?>">not-a-number</span><br />
         <input type="submit" value="validate!" />

the span (attention, inline-element) is decorated with the visibility-style-attribute which is set automatically to „hidden“ at the first request.

When submitting the first form, the controller will get the information, that step2 is going to be requested. But before including the second step, he  checks, if the entered value is a numeric . If not, the errorStyle is set to „color:red“ (and not anymore visibility:hidden) and instead of step2 the step1 is called again. But this time with a visible error-message. Otherwise the entered value is actually a number, the step2.php will be included and all is fine.

      <h1>step 2</h1>
      good job, < ?php echo $value ?> actually is a number...