PHP: проверьте, пустые ли какие-либо опубликованные vars - форма: все поля обязательны для заполнения
Есть ли более простая функция для чего-то вроде этого:
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...";
}
}
Ответы
Ответ 1
Что-то вроде этого:
// 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...";
}
Ответ 2
empty
и isset
должен сделать это.
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...
Ответ 3
Я использую свою собственную функцию...
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");
Я уверен, что его можно легко изменить для сценария. В принципе, он возвращает true, если любое из значений NULL, поэтому вы можете изменить его на пустое или другое.
Ответ 4
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
}
Ответ 5
Я сделал это вот так:
$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
}
Ответ 6
Я просто написал быструю функцию для этого. Мне нужно было обрабатывать многие формы, поэтому я сделал так, чтобы он принял строку, разделенную ",".
//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;
}
Таким образом, вы можете ввести эту функцию в свой код и обрабатывать ошибки на основе каждой страницы.
$postError = errorPOSTEmpty('login,password,confirm,name,phone,email');
if ($postError === true) {
...error code...
} else {
...vars set goto POSTing code...
}
Ответ 7
Примечание. Будьте осторожны, если 0 является допустимым значением для требуемого поля. Как упоминалось в @Harold1983, в PHP они рассматриваются как пустые.
Для таких вещей мы должны использовать isset вместо 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;
}
Ответ 8
foreach($_POST as $key=>$value)
{
if(empty(trim($value))
echo "$key input required of value ";
}
Ответ 9
Лично я извлекаю массив POST, а затем, если (! $login ||! $password), тогда echo заполнить форму:)