Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top