我试图验证三个相关的字段。这3个字段的形式已经有几十个字段,其中许多字段正在验证。
对于所讨论的3个相关字段,我需要编写代码,检查其中的一个字段是否已填充,如果其他两个字段中的任何一个未填充,则抛出一个错误。
例如:如果A和B被填充,而C不是= error。
这里是我开始的地方,但不确定这是否正确的验证:
if(!empty($post['email_notify_subject'])
&& empty($post['email_notify_date'])
&& empty($post['email_notify_emails']))
{
$errors['email_notify_date'] = 'Enter Notify Date';
$errors['email_notify_emails'] = 'Enter Notify Emails';
}
else if (empty($post['email_notify_subject'])
&& !empty($post['email_notify_date'])
&& empty($post['email_notify_emails']))
{
$errors['email_notify_subject'] = 'Enter Notify Subject';
$errors['email_notify_emails'] = 'Enter Notify Emails';
}
else if (empty($post['email_notify_subject'])
&& empty($post['email_notify_date'])
&& !empty($post['email_notify_emails']))
{
$errors['email_notify_subject'] = 'Enter Notify Subject';
$errors['email_notify_date'] = 'Enter Notify Date';
}发布于 2015-11-20 01:16:11
这怎么回事?
if (
(
! empty($post['email_notify_subject']) &&
empty($post['email_notify_date']) &&
empty($post['email_notify_emails'])
) ||
(
empty($post['email_notify_subject']) &&
! empty($post['email_notify_date']) &&
empty($post['email_notify_emails'])
) ||
(
empty($post['email_notify_subject']) &&
empty($post['email_notify_date']) &&
! empty($post['email_notify_emails'])
)
) {
// only 1 field filled out
}或者还有另一种方法:
$num_filled_out = 0;
if ( ! empty($post['email_notify_subject']) ) $num_filled_out++;
if ( ! empty($post['email_notify_date']) ) $num_filled_out++;
if ( ! empty($post['email_notify_emails']) $num_filled_out++;
if ($num_filled_out <= 1) {
// 1 or 0 filled out
}发布于 2015-11-20 01:19:53
没有对此进行测试,但是尝试一下:
<?php
if(empty(array(
$_post['email_notify_subject'],
$_post['email_notify_date'],
$_post['email_notify_emails']))){
echo "All Three filed required"; //or other instructions
}
else{
//Proceed with the form
}发布于 2015-11-20 01:21:02
这将是一种更好的方法,因为您可以在一个数组中检查所有要检查的字段和所有相应的错误消息。而且,它的可伸缩性更强。
请注意,您必须测试表单method属性是否设置为post,并且为输入字段指定了正确的名称。
$data_to_check = array(
'email_notify_subject'=>array(
'error'=>'Enter Notify Subject'
),
'email_notify_date'=>array(
'error'=>'Enter Notify Date'
),
'email_notify_emails'=>array(
'error'=>'Enter Notify Emails'
),
);
$errors = array();
foreach($data_to_check as $key => $value) {
if (empty($post[$key])) {
$errors[] = $value['error'];
}
}
if (!empty($errors)) {
foreach($errors as $key => $value) {
echo '<p class="error">'.$value.'</p>';
}
}https://stackoverflow.com/questions/33817294
复制相似问题