Page 1 of 1

function help

Posted: Tue Aug 19, 2003 5:49 am
by CrazyJimmy
Hi, i am using the following function to try validate a form :-

Code: Select all

<?php

function CheckForm($var)
{
  $valid = TRUE;
  IF (empty($var['name'])) {
  $error = array('Please Enter Name');
  $valid = FALSE;
  }
  IF (empty($var['location'])) {
  $error[] = 'Please Enter Location';
  $valid = FALSE;
  }
  for ($i = 0; $i<= count($error);$i++)
  {
  echo $error[$i].'<br>';
  }
  return $valid;
}
?>
In my main script I use the following piece of code to check if the form is valid or not. It does work, I just want to know if their is a better/correct way of doing it.

Code: Select all

<?
IF (CheckForm($_POST) == FALSE) {
  echo "try again";
  break;
  }
?>

Posted: Tue Aug 19, 2003 10:30 am
by m3rajk
i beleive post is only there if something was passed.
how about

Code: Select all

<?php

$errors=checkForm();
$complete=$errors[0];

if(!($complete)&&(isset($_POST))){  // error found
  beginPage(); showErrors(); form(); // functions that make the page
}elseif(complete){ // everything was good
  beginPage(); completed();
}else{ // give the form
  beginPage(); form();
}

function checkForm(){ // checks the form is complete
  $errors=array();
  $errors[]=TRUE; // default to not being right
  $fields=$_POST;
  if(count($fields)<4){ // not all the feilds were filled out
    $errors[0]=FALSE;
    $errors[]='Not all the fields were completed';
  }
  foreach($fields as $field=>$value){ // for each field
   switch($field){
    case('name')
      // check for this field (check against $value)
    break;
    case('name')
      // check for this field
    break;
   }
 }
 return errors;
}
?>