Jump to content

Form validation with functions


bcart

Recommended Posts

Hi there

 

I am trying to make a very simple form validation function. I currently have the following

 

function formValidate($field, $msg) {

 

if (empty($_POST['$field'])) {

$errors[] = $msg;

} else {

$field = mysqli_real_escape_string($dbc, trim($_POST['$field']));

}

 

}// end of function

 

formValidate('form', 'You forgot to enter the form');

 

 

When I run the script and enter nothing into the $_POST['form'] field it still executes an empty record into the database.

 

What am I doing wrong?

 

Cheers

Link to comment
https://forums.phpfreaks.com/topic/180985-form-validation-with-functions/
Share on other sites

You have to return the escaped value from the function.  Also, your $errors array won't work the way you want it to due to scope.

 

function formValidate($field)
{
   if(empty($_POST[$field]))
   {
      return false;
   }
   else
   {
      $field = mysqli_real_escape_string(trim($_POST[$field]));
      return $field;
   }
}

$result = formValidate('name');

if(!$result)
{
   echo "You forgot to enter your name!";
}

function Validate($Input, $Message)
{
global $errors;
if(!preg_match('~[\S]~', $Input))
	{
	$errors[] = $Message;
	return $Input;
	}
else
	{
	$Input = mysqli_real_escape_string($dbc, $Input);
	return $Input;
	}
}

$V = Validate($_POST['form'], 'You forgot to enter the form');

if(sizeof($errors) > 0))
{
//The fields were empty
}

 

You need the global $errors;

A more eloquent solution to the OP that shows how passing the errors array into the function can work:

 

$errors = array();

function formValidate($field, $msg, &$errorArray)
{
   if(empty($_POST[$field]))
   {
      $errors[] = $msg;
      return false;  //since we're returning a legit value later on in the function, I like to return a false/null value in an error condition
   }
   else
   {
      $field = mysqli_real_escape_string(trim($field));
      return $field;
   }
}

$result = formValidate('name', 'You must enter your name!', $errors);

if(count($errors) > 0)
{
   //handle errors
}
else
{
   //insert $result
}

 

I didn't mention it earlier since the OP had a problem with both return values and scope.  I figured passing an argument by reference may be too advanced for their current skill level, but since the idea of using global to 'fix' the problem came up, I figured it's best to show the right way of doing it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.