PHP Form Validation for checkbox group using php and html

Hello everyone, I am new to PHP and just started learning it. I am doing the form validation for the server side. I am totally blank how to make the checkbox input valid setting the valid variable to true making the validation for 3 or more selections.Any help will be huge. Thanks in advance

The html file linked with php validation file

<!DOCTYPE html>
<html>
<body>
<form action="a6.php" method="post">

        <label for="email">  Please enter your email address:

          <input type="text" name="email" id="email" data-validation="email">

          <!-- Display validation message for email input -->
          <?php the_validation_message('email'); ?>

        </label>
   <fieldset>
     <legend> Please select your three favorite animals:</legend>

           <input type="checkbox" name="animals[]" id="chicken" value="chicken" data-validation="checkbox_group" data-   
            validation-qty="min3">
            <label for="chicken">Chicken</label>

            <input type="checkbox" name="animals[]" id="cow" value="cow" data-validation="checkbox_group" data-  
            validation-qty="min3">
            <label for="cow">cow</label>

            <input type="checkbox" name="animals[]" id="whale" value="whale" data-validation="checkbox_group" data-
             validation-qty="min3">
             <label for="whale">whale</label>

            <input type="checkbox" name="animals[]" id="bee" value="bee" data-validation="checkbox_group" data-
             validation-qty="min3">
             <label for="bee">  bee</label>

            <input type="checkbox" name="animals[]" id="doggo" value="doggo" data-validation="checkbox_group" data-
             validation-qty="min3">
             <label for="doggo">doggo</label>

            <input type="checkbox" name="animals[]" id="kitten" value="kitten" data-validation="checkbox_group" data-
             validation-qty="min3">
             <label for="kitten">kitten</label>

            <input type="checkbox" name="animals[]" id="jellyfish" value="jellyfish" data-validation="checkbox_group" data-
             validation-qty="min3">
             <label for="jellyfish">jellyfish</label>
     </fieldset>
        <label for="date">  Please enter your favorite date: (yyyy/mm/dd)

          <input type="text" name="date" id="date" data-validation="date" data-validation-format="yyyy/mm/dd">

          <!-- Display validation message for date input -->
          <?php the_validation_message("date"); ?>
        </label>

        <input type="reset" name="" value="Reset Form">

        <input type="submit" value="Submit Form">
</form>
</body>
</html>

The php validation file:

<?php
// Global result of form validation
$valid = false;
// Global array of validation messages. For valid fields, message is ""
$val_messages = Array();
// Check each field to make sure submitted data is valid. If no boxes are checked, isset() will return false
function validate()
{
    global $valid;
    global $val_messages;
    array_push($val_messages, "email is not correct format", "please enter a valid date in the format yyyy/mm/dd", 
      "please choose atleast three animals",""
    );

    if($_SERVER['REQUEST_METHOD']== 'POST')
    {
      // Use these patterns to check email and date, or come up with your own.
      // email: '#^(.+)@([^\.].*)\.([a-z]{2,})$#'
      // date: '#^\d{4}/((0[1-9])|(1[0-2]))/((0[1-9])|([12][0-9])|(3[01]))$#'

       if(isset($_POST['email']) == true && isset($_POST['date']) == true && isset($_POST['animals']) == true){
          if(!preg_match('#^(.+)@([^\.].*)\.([a-z]{2,})$#', 'email')){
            return $valid;
          } else if(!preg_match('#^\d{4}/((0[1-9])|(1[0-2]))/((0[1-9])|([12][0-9])|(3[01]))$#', 'date')){
             return $valid;
          } else{
              $valid = true;
          }

         /*for($i=0;$i<count($_POST['animals']);$i++){

         }*/
       }  
    }
}
?>

What are you trying to validate against?

Hello @astonecipher,
How are you?
Thank you for your response. I actually solved this part today :grinning:
Thank you

Normally, you wouldn’t be sending in strings, you would send in identifiers. So,

$animals = [
   0 => 'chicken',
   1 => 'cow',
   2 => 'whale',
   3 => 'bee',
]

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
     // Now check if the key exists for what was passed in.
}

This isn’t needed at all. It is woefully outdated.

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// the email is not a valid format
}

Ok. How would I check if 3 or more checkboxes are selected or not using this format?

This block of quote is more cleaner :slight_smile: Thanks for suggesting this way

<?php


$_POST['animal'][] = 1;
$_POST['animal'][] = 2;
// $_POST['animal'][] = 0;

$animals = [
   0 => 'chicken',
   1 => 'cow',
   2 => 'whale',
   3 => 'bee',
];

$selected = [];
foreach($_POST['animal'] as $k=>$v) {
	if(array_key_exists($v, $animals)){
		array_push($selected, $animals[$v]);;
	}	
}

if(count($selected) >=3)
   print_r($selected);
else
   echo "You only selected " . count($selected);

What is the role of this? I don’t understand this

Normally those values are passed in via form. That assigns values without needing the form, for testing purposes

oh I see. Ok
Thank you so much for your time and explaining me in detail. I appreciate it :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service