johnmogi
johnmogi

Reputation: 21

minimum characters on gravity forms field

Really trying to make minimum characters on a field- has tried this:

// Added custom validation for minimum word count
add_filter("gform_field_validation_11_70", "validate_word_count", 10, 4);

function validate_word_count($result, $value, $form, $field){
if (str_word_count($value) < 150) //Minimum number of words
{
    $result["is_valid"] = false;
    $result["message"] = "Please enter at least 150 words.";
}
return $result;
}

But I'm looking for a way to validate characters not words...

Upvotes: 1

Views: 4807

Answers (3)

Omar Tanti
Omar Tanti

Reputation: 1448

I had the same 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;
}

Upvotes: 1

johnmogi
johnmogi

Reputation: 21

Your solution looks very good- thanks!, however: Ended up using the following:

    // Added custom validation for minimum characters count
    add_filter("gform_field_validation_3_8", "validate_chars_count", 10, 4);
    add_filter("gform_field_validation_1_5", "validate_chars_count", 10, 4);
    function validate_chars_count($result, $value, $form, $field){
if (strlen($value) < 9) { //Minimum number of characters
    $result["is_valid"] = false;
    $result["message"] = "Please enter at least 9 numbers.";
}
return $result;
    }

Since I'm trying to do a phone number validation, I would like to limit the user to fill in only numbers or "-" could this be achieved in Gravity Forms?

Upvotes: 1

Dave from Gravity Wiz
Dave from Gravity Wiz

Reputation: 2859

Replacing the "str_word_count()" function, just use "strlen()" instead.

Also, I've written this as a snippet so you can apply different limits to different fields more easily:

https://gist.github.com/spivurno/8220561

Copy and paste the snippet into your theme's functions.php file and then modify the configuration at the bottom for your form. You can apply this to different forms and fields by copying and pasting this configuration and modifying the parameters for the form/field you want.

new GW_Minimum_Characters( array(
    'form_id' => 385,
    'field_id' => 1,
    'min_chars' => 4,
    'validation_message' => __( 'Oops! You need to enter at least %s characters.' )
) );

Upvotes: 0

Related Questions