TunaFFish
TunaFFish

Reputation: 11302

PHP: check if any posted vars are empty - form: all fields required

Is there a simpler function to something like this:

if (isset($_POST['Submit'])) {
    if ($_POST['login'] == "" || $_POST['password'] == "" || $_POST['confirm'] == "" || $_POST['name'] == "" || $_POST['phone'] == "" || $_POST['email'] == "") {
        echo "error: all fields are required";
    } else {
        echo "proceed...";
    }
}

Upvotes: 42

Views: 173597

Answers (10)

Mustafa Özyurt
Mustafa Özyurt

Reputation: 26

if (array_filter(["param1", "param2", "param3"],
    fn(string $param) => !array_key_exists($param, $_POST))) {
        throw new Exception('Missing element');
}

Upvotes: 1

foreach($_POST as $key=>$value)
{

   if(empty(trim($value))
        echo "$key input required of value ";

}

Upvotes: -1

bharadwaja Gummadi
bharadwaja Gummadi

Reputation: 305

Note : Just be careful if 0 is an acceptable value for a required field. As @Harold1983- mentioned, these are treated as empty in PHP. For these kind of things we should use isset instead of empty.

$requestArr =  $_POST['data']// Requested data 
$requiredFields = ['emailType', 'emailSubtype'];
$missigFields = $this->checkRequiredFields($requiredFields, $requestArr);

if ($missigFields) {
    $errorMsg = 'Following parmeters are mandatory: ' . $missigFields;
    return $errorMsg;
}

// Function  to check whether the required params is exists in the array or not.
private function checkRequiredFields($requiredFields, $requestArr) {
    $missigFields = [];
    // Loop over the required fields and check whether the value is exist or not in the request params.
    foreach ($requiredFields as $field) {`enter code here`
        if (empty($requestArr[$field])) {
            array_push($missigFields, $field);
        }
    }
    $missigFields = implode(', ', $missigFields);
    return $missigFields;
}

Upvotes: -1

user1518699
user1518699

Reputation: 407

I just wrote a quick function to do this. I needed it to handle many forms so I made it so it will accept a string separated by ','.

//function to make sure that all of the required fields of a post are sent. Returns True for error and False for NO error  
//accepts a string that is then parsed by "," into an array. The array is then checked for empty values.
function errorPOSTEmpty($stringOfFields) {
        $error = false;
            if(!empty($stringOfFields)) {
                // Required field names
                $required = explode(',',$stringOfFields);
                // Loop over field names
                foreach($required as $field) {
                  // Make sure each one exists and is not empty
                  if (empty($_POST[$field])) {
                    $error = true;
                    // No need to continue loop if 1 is found.
                    break;
                  }
                }
            }
    return $error;
}

So you can enter this function in your code, and handle errors on a per page basis.

$postError = errorPOSTEmpty('login,password,confirm,name,phone,email');

if ($postError === true) {
  ...error code...
} else {
  ...vars set goto POSTing code...
}

Upvotes: -1

Calin Rusu
Calin Rusu

Reputation: 59

I did it like this:

$missing = array();
 foreach ($_POST as $key => $value) { if ($value == "") { array_push($missing, $key);}}
 if (count($missing) > 0) {
  echo "Required fields found empty: ";
  foreach ($missing as $k => $v) { echo $v." ";}
  } else {
  unset($missing);
  // do your stuff here with the $_POST
  }

Upvotes: 0

Nahser Bakht
Nahser Bakht

Reputation: 930

if( isset( $_POST['login'] ) &&  strlen( $_POST['login'] ))
{
  // valid $_POST['login'] is set and its value is greater than zero
}
else
{
  //error either $_POST['login'] is not set or $_POST['login'] is empty form field
}

Upvotes: 5

animuson
animuson

Reputation: 54729

I use my own custom function...

public function areNull() {
    if (func_num_args() == 0) return false;
    $arguments = func_get_args();
    foreach ($arguments as $argument):
        if (is_null($argument)) return true;
    endforeach;
    return false;
}
$var = areNull("username", "password", "etc");

I'm sure it can easily be changed for you scenario. Basically it returns true if any of the values are NULL, so you could change it to empty or whatever.

Upvotes: 3

Jacob Relkin
Jacob Relkin

Reputation: 163228

empty and isset should do it.

if(!isset($_POST['submit'])) exit();

$vars = array('login', 'password','confirm', 'name', 'email', 'phone');
$verified = TRUE;
foreach($vars as $v) {
   if(!isset($_POST[$v]) || empty($_POST[$v])) {
      $verified = FALSE;
   }
}
if(!$verified) {
  //error here...
  exit();
}
//process here...

Upvotes: 2

Harold1983-
Harold1983-

Reputation: 3369

Something like this:

// Required field names
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');

// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
  if (empty($_POST[$field])) {
    $error = true;
  }
}

if ($error) {
  echo "All fields are required.";
} else {
  echo "Proceed...";
}

Upvotes: 82

Doug Molineux
Doug Molineux

Reputation: 12431

Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)

Upvotes: -2

Related Questions