How to Set a Minimum and a Maximum Number of Choices for a Checkbox


Would you like to set a minimum and a maximum number of choices for your Checkbox form field? Inside the form builder, you can already set a maximum number for this field. However, using a little PHP snippet did you know you can also force a minimum amount as well? In this tutorial, we’ll show you the PHP code snippet needed to complete this.


You can already set up your forms to set a maximum number of choices for your Checkbox field by following the steps in this tutorial.

1) Setting up the form

First, set up your form to add a Checkbox field and set the maximum number to match your needs. In our example, we’ve set our Choice Limit to three so only up to three selections can be chosen.

Set the maximum number of choices visitors can choose on your checkbox

2) Adding the PHP

Next, you’ll need to copy the code snippet below and add it to your site. In our code, we’re going to target the form ID of 787 and the field ID of the Checkbox form field of 11. This code is checking to make sure at least two items have been selected from the list.

 * Set minimum and maximum number of choices on Checkbox
 * @link
function wpf_dev_process( $fields, $entry, $form_data ) {
    // Optional, you can limit to specific forms. Below, we restrict output to
    // form #787.
    if ( absint( $form_data['id'] ) !== 787 ) {
        return $fields;
    // check the field ID 11 has at least one selection made    
    if($fields[11]['value'] <= 1) 
            // Add to global errors. This will stop form entry from being saved to the database.
            // Uncomment the line below if you need to display the error above the form.
            // wpforms()->process->errors[ $form_data['id'] ]['header'] = esc_html__( 'Some error occurred.', 'plugin-domain' );    
            // Check the field ID 11 and show an error message at the top of the form and under the specific field
               wpforms()->process->errors[ $form_data['id'] ] [ '11' ] = esc_html__( 'Please make sure there are at least 2 options selected.', 'plugin-domain' );
            // Add additional logic (what to do if error is not displayed)
add_action( 'wpforms_process', 'wpf_dev_process', 10, 3 );

Please remember to update the code above to match your form ID and field ID. If you need any help finding those ID numbers, please review this documentation.

Now if a visitor tries to submit the form with only one selection, they will see this error.

Visitors will see an error message below the field if the user hasn't selected the minimum number of choices

And that’s all you need to set a min and max number of choices on your checkboxes. Would you like to customize the look of these checkboxes? Take a look at our article on How to Customize Checkbox and Radio Fields to Look Like Buttons.

Action reference: wpforms_process