TNK
TNK

Reputation: 4323

validate checkboxes using php

I have a form with series of checkboxes with the same name of 'name=category[]'. And now I need to count how many checkboxes are selected by a user. Further I need to check at least 1 checkbox is being selected or upto 10 checkboxes.

This is the way that I am trying so far...

if ( isset ( $_POST['category']) {

  if (( sizeof( $_POST['category']) == 10 || sizeof( $_POST['category']) <= 10 )) {

     // form processing....

  } else {

      echo 'Atleast 1, not more than 10 categories.';
  }

} else {

  echo 'Please select atleast one category.';

}

can anybody tell me is there an another way to accomplish this task? That mean, to get this two errors...

Upvotes: 0

Views: 352

Answers (2)

Priya
Priya

Reputation: 1554

As per your question you want to check only the selected checkbox count.

As per my knowledge the values for checkbox are either 'on' or 'off'. If you will make a count of the name 'category' it'll give you all checkbox count displayed on the page irrespective of clicked or not-clicked.

so filter it out and count

put this function before if condition starting. Formated code...


    function nonzero($var) {
        return $var !="off" ? "on" :'';
    }
    if ( isset ( $_POST['category']) { 
        $_POST['category'] = array_filter($_POST['category'], 'nonzero');
        if ( sizeof( $_POST['category'] ) >= 1 //check of at-least one is checked
             && sizeof( $_POST['category'] ) <= 10 ) { //check for at-most 10 is checked
            form processing();
        } else { 
            echo 'At-least 1, not more than 10 categories.'; 
        } 
    } else { 
        echo 'Please select at-least one category.'; 
    } 

Upvotes: 1

MrCode
MrCode

Reputation: 64526

When handling input arrays, it's good to check it is an array as well as isset:

if (isset($_POST['category']) && is_array($_POST['category'])) {

  $totalChecked = count($_POST['category']);

  if ($totalChecked >= 1 && $totalChecked <= 10) {

     // form processing....

  } else {
      echo 'Atleast 1, not more than 10 categories.';
  }

} else {
  echo 'Please select atleast one category.';
}

Upvotes: 1

Related Questions