function help

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
CrazyJimmy
Forum Commoner
Posts: 34
Joined: Tue Nov 19, 2002 1:40 pm

function help

Post 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;
  }
?>
m3rajk
DevNet Resident
Posts: 1191
Joined: Mon Jun 02, 2003 3:37 pm

Post 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;
}
?>
Post Reply