0

I've been working on a formmail and I'm trying to get two checkboxes to work. I can get them to echo the correct information but I want the user to be alerted when they haven't picked at least one checkbox. This is my code:

HTML

<td>
     <input type="checkbox" name="date1" value="Yes">July 7-11
</td>
<td>
     <input type="checkbox" name="date2" value="Yes">July 14-18
<td>

PHP

$date1 = $_POST['date1']; // required
$date2 = $_POST['date2']; // required

    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$date1)) {
    $error_message .= 'You did not choose a date.<br />';
  }

    $string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$date2)) {
    $error_message .= 'You did not choose a date.<br />';
  }

$email_message .= "July 07-11: ".clean_string($date1)."\n"; 
$email_message .= "July 14-18: ".clean_string($date2)."\n";

It makes me choose both checkboxes before it will send the email. I've tried having the inputs have two values and forcing at least one but I can't seem to get anything to work.

  • 1
    What is the point of a preg_match on something that will be Yes? – Devon Apr 17 '14 at 17:53
  • why dont you use radio boxes instead of check boxes? – artur99 Apr 17 '14 at 18:20
  • Devon - I've just been playing around with different code and was trying to get something to work using the "Yes." artur99 - I want a checkbox because I want the user to be able to have the option for both dates if they want, but at least one date must be chosen. – elfshadowreaper Apr 17 '14 at 18:24

1 Answers1

0

Checkboxes are not set to anything if not checked. If checked, you know the value - it was sent. So, you only need to check if they were set.

if(!isset($_POST['date1']) && !isset($_POST['date2']))
    $error_message = 'You did not choose a date.<br>';

Note: This does not ensure a person used the form. I could hard-code my own values for date1 and date2 in my own form, submitted to your website.

kainaw
  • 4,033
  • 1
  • 14
  • 30