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

后端 未结 9 1398
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 15:16

Is there a simpler function to something like this:

if (isset($_POST[\'Submit\'])) {
    if ($_POST[\'login\'] == \"\" || $_POST[\'password\'] == \"\" || $_P         


        
相关标签:
9条回答
  • 2020-11-27 15:56

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

    0 讨论(0)
  • 2020-11-27 15:59

    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...";
    }
    
    0 讨论(0)
  • 2020-11-27 16:07

    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;
    }
    
    0 讨论(0)
提交回复
热议问题