Search code examples
wordpressgravity-forms-plugingravityforms

Gravity Forms: Require minimum/maximum characters in input field


is it possible to limit the characters in an input field for every form we have? I need an input field with exact 5 numbers (zip field).

I found this solution: (full code here: https://gravitywiz.com/require-minimum-character-limit-gravity-forms/)

new GW_Minimum_Characters( array( 
    'form_id' => 524,
    'field_id' => 1,
    'min_chars' => 4,
    'max_chars' => 5,
    'min_validation_message' => __( 'Oops! You need to enter at least %s characters.' ),
    'max_validation_message' => __( 'Oops! You can only enter %s characters.')
    ) 
);

The problem is, that we have dozens of forms and couldn't build a function for all of them ;) So we couldn't use the "form_id" and the "field_id".

Maybe there is a way to use a parameter name for the input field?


Solution

  • I had a similar issue where I needed to have minimum no. of characters for text fields and textarea. This setting had to be used in different forms and multiple fields therefore I could not add filters with pre-defined form ids and field ids.

    What I did is that I created a new setting which was visible when editing a field and then I validated the submission. You can use the code below:

    add_action( 'gform_field_standard_settings', 'minimum_field_setting', 10 );
    add_action( 'gform_editor_js', 'editor_script' );
    add_filter( 'gform_tooltips', 'add_encryption_tooltips' );
    add_filter( 'gform_validation', 'general_validation' );
    
    /**
     * Adds the Minimum Characters Field to Form Fields
     *
     * @param integer $position
     */
    function minimum_field_setting( $position ) {
    
        //Position: Underneath Description TextArea
        if ( $position == 75 ) {
            ?>
            <li class="minlen_setting field_setting">
                <label for="field_minlen" class="section_label">
                    <?php esc_html_e( 'Minimum Characters', 'gravityforms' ); ?>
                    <?php gform_tooltip( 'form_field_minlen' ) ?>
                </label>
                <input type="number"
                       id="field_minlen"
                       onblur="SetFieldProperty('minLength', this.value);"
                       value=""
                />
            </li>
            <?php
        }
    }
    
    /**
     * Adds Javascript to Gravity Forms in order to render the new setting field in their appropriate field types
     */
    function editor_script() {
        ?>
        <script type='text/javascript'>
            //Append field setting only to text and textarea fields
            jQuery.each(fieldSettings, function (index, value) {
                if (index === 'textarea' || index === 'text') {
                    fieldSettings[index] += ", .minlen_setting";
                }
            });
            //binding to the load field settings event to initialize the checkbox
            jQuery(document).bind("gform_load_field_settings", function (event, field, form) {
                if (field.type === 'textarea' || field.type === 'text') {
                    console.log(field);
                    if (typeof field.minLength !== "undefined") {
                        jQuery("#field_minlen").attr("value", field.minLength);
                    } else {
                        jQuery("#field_minlen").attr("value", '');
                    }
                }
            });
        </script>
        <?php
    }
    
    /**
     * Add GF Tooltip for Minimum Length
     *
     * @param array $tooltips
     *
     * @return mixed
     */
    function add_encryption_tooltips( $tooltips ) {
        $tooltips['form_field_minlen'] = "<h6>Minimum Length</h6>Minimum number of characters for this field";
    
        return $tooltips;
    }
    
    /**
     * Validate Form Submission
     *
     * @param array $validation_result
     *
     * @return mixed
     */
    function general_validation( $validation_result ) {
        $form = $validation_result['form'];
    
        foreach ( $form['fields'] as &$field ) {
            if ( in_array( $field->type, [ 'text', 'textarea' ] ) && ! empty( $field->minLength ) ) {
                $input_name = 'input_' . $field->id;
                if ( isset( $_POST[ $input_name ] ) && $_POST[ $input_name ] != '' ) {
                    if ( strlen( $_POST[ $input_name ] ) < (int) $field->minLength ) {
                        $field->failed_validation      = true;
                        $field->validation_message     = 'Field must contain at least ' . $field->minLength . ' characters';
                        $validation_result['is_valid'] = false;
                    }
                }
            }
        }
        $validation_result['form'] = $form;
    
        return $validation_result;
    }
    

    You can change the setting from Minimum Length to Exact Length and then update the validation accordingly.