如果一个字段不为空,则所有必填字段都不为空


if one field is not empty then all required not empty

是否有一种有效的方法来处理具有三个输入字段的表单的一部分。如果所有的都是空的,那么什么都不要做,但如果有一个被填满了,那么所有的都必须被填满。

目前我有这个

if (isset($_POST['desc1']) && !empty($_POST['desc1'])){
$email_message .= $_POST['desc1']. " - " . $_POST['code1']. " - Amount: " .$_POST['quant1']."<br>";
$toadd .= $_POST['desc1']. " - " . $_POST['code1']. " - Amount: " .$_POST['quant1']."<br><br>"; 
}

问题是,他们可能输入了desc1,但没有输入code1quant1,而且它无论如何都会激发。如果他们输入了code1quant1,而不是desc1,则不会发生任何事情,这又是一个问题,我想将其显示为错误,并让他们返回并重试。

有很多方法可以实现这一点。

$required = array('desc1', 'code1', 'quant1');
$errors = array();
$fields_set = 0;
foreach ($required as $rq) {
    if (isset($_POST[$rq])) {
        $fields_set++;
    } else {
        $errors[$rq] = "{$rq} is not set...";
    }
}
$valid = ($fields_set == 0 || $fields_set == count($required)) ? true : false;
if ($valid) {
    // do stuff
} else {
    print_r($errors);
}

你的意思是这样的吗?

if(!isset($_POST['desc1']) &&
   !isset($_POST['code1']) &&
   !isset($_POST['quant1'])  {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
   }
elseif(!isset($_POST['desc1']) ||
   !isset($_POST['code1']) ||
   !isset($_POST['quant1'])  {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
   }