How to Limit Range Allowed in Numbers Field

Overview

Would you like to limit the range allowed in the Numbers Field with WPForms? Using JavaScript you can limit the number a user selects no more than a certain number? This tutorial will show you how to use a custom code snippet to easily achieve limiting the range for your Numbers field.

In HTML, the numbers input element allows for min and max attributes, which define the minimum and maximum values that can be added to the input field.

Setup

In the snippet below, we’ll use jQuery to add min and max attributes to specific Numbers field in WPForms.

1) Adding the JavaScript

Adding this code will apply a minimum value of 23 and a maximum value of 40 to any Numbers field with a CSS class named wpf-num-limit.

/**
 * Limit number range allowed for a Numbers field
 * Apply the class "wpf-num-limit" to the field to enable.
 *
 * @link https://wpforms.com/developers/how-to-limit-range-allowed-in-numbers-field/
 *
 */

function wpf_dev_num_limit() {
    ?>
    <script type="text/javascript">
        jQuery(function($){
            $('.wpf-num-limit input').attr({'min':23, 'max':40}); // Define number limits
        });
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_num_limit', 30 );

2) Adding the CSS Class

To add this class to a field, you’ll need to open the form builder, click the field to open its Field Options panel, and open the Advanced Options section.

Next, add wpf-num-limit to the CSS Classes field.

Adding the CSS class will now limit the range allowed for the number field

Once you’ve saved the form, users will now see a validation error if they add a number that falls outside of the range defined in that code.

Using a small JS snippet you can set a min and max number allowed on the numbers field

And that’s it! You’ve now set a minimum and a maximum number allowed for your Numbers field. Would you like to change the required field indicator? Take a look at our article on How to Change Required Field Indicator.

Action Reference: wpforms_wp_footer_end