form validation, functions to validate fields

A

Anonymous

Guest
this is a portion of a script i'm working on to validate fields in a form
what am i doing wrong?
no matter what i do it returns as though nothing's wrong

PHP:
<?
$errors=0;
$error="The following errors have occured while processing you input<ul>";

function isempty($var)
{
  if($var=="")
    {$errors=1; $error.="<li>You did not enter one or more of the required fields. Please go back and try again.</li>";}
}
$error.="</ul>";

isempty($field);

if ($errors==1) echo $error;
?>
 
chrisklapp said:
this is a portion of a script i'm working on to validate fields in a form
what am i doing wrong?
no matter what i do it returns as though nothing's wrong

PHP:
<?
$errors=0;
$error="The following errors have occured while processing you input<ul>";

function isempty($var)
{
  if($var=="")
    {$errors=1; $error.="<li>You did not enter one or more of the required fields. Please go back and try again.</li>";}
}
$error.="</ul>";

isempty($field);

if ($errors==1) echo $error;
?>

When you create a variable inside a function, it only exists inside the function. This is called variable scope, and there's a whole section about it in the manual.

If you want to access an outside variable from inside the function, you need to use the global keyword. However, usually you can (and often ought to) do without using global:
PHP:
<?php
function get_error($var) {
/* Returns false if there is no error, otherwise returns a string with the
   error message. */
    
   if(empty($var)) { // empty is a built-in function; use it
      // the var is empty, return an error string
      return 'You did not enter one or more of the required fields.';
   }
	
   return false;
}

if($error = get_error($field)) {
   echo "The following errors have occured while processing you input:\n" .
   echo "<ul>\n";
   echo '<li>' . $error . "</li>\n";
   echo "</ul>\n";
}
?>

In the above, it's quite easy to call get_error() on multiple fields and add them to an array, so you can cycle through them and display error messages for each, if necessary. (Validating form fields is a big, ugly problem and always has been, and if you're in the position of having to do this for lots of different forms, I suggest that you fall back on one of the many solutions that have already been created.)
 
Back
Top