Checkboxes: Validation & Stickiness

Dumb question, but do I really have to do any validation for a form with only Checkboxes on it?

Also, do I need the concept of “stickiness”?

I’ve never worked with Checkboxes before, but it seems like they are binary - either you checked one or not - so what form validation would I need to do? (It’s not like a Textbox where you might display an error like “Comments can only be 1024 character long. Your response is 2000 character long!”)

As such, would I need a “Sticky Form” if the end user really can’t screw things up?

Hope that makes sense…

Thanks.

I could go in my dev tools and change what value is going to be sent server side. So yes.

Here is what I have as a demo…

    <form id="changeInterests" action="" method="post">
        <label><input id="interest_01" name="interest[]" type="checkbox" value="Football"> Football</label><br/>
        <label><input id="interest_02" name="interest[]" type="checkbox" value="Basketball"> Basketball</label><br/>
        <label><input id="interest_03" name="interest[]" type="checkbox" value="Baseball"> Baseball</label><br/>

        <!-- Submit Form -->
        <input type="submit" name="changeInterests" class="button" value="Change Interests"/>
        <input type="reset" name="changeInterests" class="button" id="reset" value="Cancel" />

    </form>

The solution I am working towards would be database driven and dynamic using arrays.

So you are saying I need to go in and somehow check that every checkbox has a valid value?

What I am confused about is that I don’t see where you would be displaying data validation errors to the end user like a regular form.

On my normal forms, I will display an error message in red if you enter a wrong value in a Textbox, for instance.

This script I am working on is just going to be a page of maybe 100 hobbies, where the user chooses their Top-5 Favorite Hobbies.

To me there doesn’t seem to be much to check, but then I have never used Checkboxes before, so I feel uncomfortable with this entire last-minute request… :confounded:

Then you should be building your form dynamically and using the same array of options to validate POST.
Partial sample.

<?php
$interests = array();
//Build from query result
//$interests[] = $row['interest']; 

//Sample
$interests = array("Football","Basketball","Baseball");    


//POST validate
if(isset($_POST['interest'])):
    $cnt=0;
    foreach($_POST['interest'] as $interest):
        //Validate
        if(in_array($interest,$interests)):
            $cnt++;
            //Check count
            if($cnt <= 5):    
                //Do processing of first five here
            
            endif;
        
        
        endif;
    endforeach;

endif;

//Form Output
$id_num = 1;
foreach($interests as $item):
    echo '<label><input id="interest_' . $id_num . '" name="interest[]" type="checkbox" value="' . $item . '"> ' . $item . '</label><br />'."\r";
    $id_num++;
endforeach;
?>
1 Like

You also mentioned “stickiness” in your other thread. In the same way, you build an array of the user interests and while looping through all interests, check if it is in the user interests array.

<?php
$interests = array();
//Build from query result
//$interests[] = $row['interest']; 

//Sample
$interests = array("Football","Basketball","Baseball");
    
////////////////
//User interests 

$Userinterests = array();
//Build from query result
//$Userinterests[] = $row['interest']; 

//Sample
$Userinterests = array("Basketball");    

//POST validate
if(isset($_POST['interest'])):
    
    $cnt=0;
    foreach($_POST['interest'] as $interest):
        //Validate
        if(in_array($interest,$interests)):
            $cnt++;
            //Check count
            if($cnt <= 5):    
                //Do processing of first five here
            
            endif;
        
        
        endif;
    endforeach;

endif;
?>
<form action="" method="post">
<?php
    $id_num = 1;
    foreach($interests as $item):
        $selected_interest = (in_array($item,$Userinterests) ? ' checked="checked"' : '');
        echo '<label><input id="interest_' . $id_num . '" name="interest[]" type="checkbox" value="' . $item . '"' . $selected_interest . '> ' . $item . '</label><br />'."\r";
        $id_num++;
    endforeach;
?>    
<!-- Submit Form -->
    <input type="submit" name="changeInterests" class="button" value="Change Interests"/>
    <input type="reset" name="changeInterests" class="button" id="reset" value="Cancel" />
</form>

Thanks for the samples. As usual, I bit off more than I can chew. I have an idea of what I want to do, now it is just putting it all together. So much for having this done by suppertime?! :slight_smile: (I probably just added another week onto things if I do this the way I want, but we’ll see…)

For checkboxes where you have predefined the valid values in the checkboxes themselves you could simply sanitize them rather than validating - just discard any that don’t have a valid value. The only time any would have an invalid value is if someone tampered with the form or the data being sent and so they already know the value they sent is invalid so you don’t need to tell them.

1 Like

That is what I was thinking.

Either you checked an Interest and it is a Yes/TRUE/1 or you didn’t check it and it is a No/FALSE/0/NULL. Anything else is bogus, and I don’t feel compelled in that case to help you out, because you are likely a hacker!!

Be careful as your form identifies the values as Football, Baseball, etc. So don’t check for Yes/TRUE/1. :wink:

Yes, if you build an array like I did then use this to build your form as well as compare POST values you should be fine. If the “Junk” value is not in the array, it won’t be passed through to DB.

See, I told you I don’t know anything about Checkboxes!!! :blush:

Okay, I am confused…

If I have the following Checkboxes in my Form…

__ Football
__ Basketball
__ Baseball
__ Hockey

What should the value be in the HTML??

Should it be the name of the Interest (e.g. “Football”)?

Or should it be a simple binary (e.g. “Yes”, “TRUE”)?

Here is some sample code of what I had this morning…

    <form id="changeInterests" action="" method="post">
        <label><input id="interest_01" name="interest[]" type="checkbox" value="Football"> Football</label><br/>
        <label><input id="interest_02" name="interest[]" type="checkbox" value="Basketball"> Basketball</label><br/>
        <label><input id="interest_03" name="interest[]" type="checkbox" value="Baseball"> Baseball</label><br/>
    </form>

Still trying to learn how to do all of this correctly!!

I think it should be the name of the interest. It gives you a unique value you can compare to on POST. if you put “Yes” or “TRUE” then you are going to need to figure out what this means on processing and without forced keys or some other way to identify the value it would be almost impossible as only selected checkboxes are passed and if they all say “true” then what? Use the name.

But remember, Drummin, I have name-interest[ ] so when the form gets submitted, each Checkbox that was checked would have a unique ID, right?

And the value= in this case wouldn’t need to be unique since there is a Key/ID to go along with it, right?

For example…

KEY    VALUE
3    Yes
6    Yes
8    Yes

So it would seem it would be easier on my PHP to just iterate through the array and if look for “Yes”.

Although, thinking out loud, I believe the way Checkboxes work is that if you check them they get submitted in the $_POST array, and if they are unchecked then they never get sent over. Point being, just the presence of an item in the items array means that it was checked, regardless of whether it is “Yes” or “Football” or whatever, right??

I think either way of coding the inputs would be easy enough to do.
Either
<input name="football"
<input name="baseball"
or
<input name="interest[]" value="football"
<input name="interest[]" value="baseball"

could work.

Well just using my little example, you will notice the KEYs are not always what you might expect.

<label><input id="interest_1" name="interest[]" type="checkbox" value="Football"> Football</label><br />
<label><input id="interest_2" name="interest[]" type="checkbox" value="Basketball"> Basketball</label><br />
<label><input id="interest_3" name="interest[]" type="checkbox" value="Baseball"> Baseball</label><br />

Say I pick Basketball, ( id=“interest_2” ) What key do you think it would be?

Array
(
    [interest] => Array
        (
            [0] => Basketball
        )

    [changeInterests] => Change Interests
)

Now if I pick Football and Basketball, will Basketball still have a KEY of zero? NO.

Array
(
    [interest] => Array
        (
            [0] => Football
            [1] => Basketball
        )

    [changeInterests] => Change Interests
)

As Mittineague suggested either use the interest name as a unique NAME or the VALUE with an interest NAME array.

In either case, build it dynamically. Don’t hand code 100 options. As I mentioned, you also can use this same array to validate user input.

@Drummin,

I feel like we are having two separate conversions - which isn’t the first time.

All along I have said I am building things dynamically. Where did this hard-coding thing come in?

And I don’t feel like you read anything I said in my last post.

I don’t see where have this…

KEY    VALUE
3    Baseball
6    Camping
8    Knitting

Provides any more value than this…

KEY    VALUE
3    Yes
6    Yes
8    Yes

In each case, I know WHICH Checkbox was checked…

Care to share why you feel one creates an issue?

I am basing my answer on the code you posted in post #3 where you have open keys, e.g. name=“interest

IF these were input type=“text” then each input would be posted and each key would be incremental starting with zero. Checkboxes are only sent if checked, and again the keys would be incremental starting with zero.

So unless you are forcing keys, I don’t see how Baseball can have a key of 3, unless of course it was the fourth item on the list that was checked.

Probably the best way to see WHAT is being passed would be to print your POST.


echo "<pre>"; 
print_r($_POST); 
echo "</pre>"; 

1 Like

Okay, I see where our “Communication Breakdown” was at! :smile:

Yes, since this morning I have created a table to stores all of Interests. Each has a unique ID. And when I populate my form, I will take the table data, stick it into an array, and then use the array to populate the Checkboxes on the form.

So regardless of which Checkboxes are chosen, then array containing the Checkbox responses - in the $_POST array - should look like I was saying in Post #14.

And the point I was trying to make was that the “Value” shouldn’t really matter if each Checkbox will always have the same Key/ID value, right?

So you now ARE forcing the KEY with an ID number… Is that right? Then if you have an ID number then it wouldn’t matter what value you used. If you are still using open keys then you still have a problem I was talking about. Hey, print_r($_POST) see if it returns what you expect.

Let’s say I have a universe of 10 Interests in my table. Each has a unique ID. When I build the Form, I query the database, get those 10 Interests with their IDs, then stick those in an array,and then use the array to populate the Checkboxes.

So, yes, each Checkbox has something like - I haven’t mastered the code yet…

<?php
echo "<input id='interest_" . $interestID . "' name='interest[" . $interestID . "]' type='checkbox' value='DoesThisReallyMatter'>";
?>