How to require whole numbers in Gravity Forms' Number field
The Number Field in Gravity Forms allows users to enter decimals. If you want to force the number to be an integer (whole numbers, including negative numbers), you can add this code below.
This code will work with Gravity Forms' Range Min and Max settings; if you want only to allow year values, you can set the Min to 1900
, for example. For age values, you could set the Min to 0
and the max to 130
.
Note: For this code to work, ensure the Output HTML5 setting is enabled in Gravity Forms Settings.
add_filter( 'gform_field_content', function ( $field_content, $field ) { if ( 'number' !== $field->type ) { return $field_content; } return str_replace( "step='any'", "step='1'", $field_content ); }, 10, 2 );
Read here how to add these code samples to your website: Where to put code samples.
If you want this to modify only one form or only a single field for a form, modify the filter's name as described in the Usage section of the Gravity Forms docs site.