GravityForms add Custom Validation for Textbox field with minimum and maximum Word count without plugin

GravityForms add minimum maximum Word Validation to textbox without plugin

If you want to add minimum and maximum word count validation to your GravityForm textarea field then it is not possible with the plugin. You can set maximum letters count. But limit of words is not possible. You have to either use any third-party premium addon for this or you have to add your own custom filter using the GravityForms filters.

In this tutorial I will show you how we can add minimum and maximum word limit validation to textbox.

Gravityforms provided custom filters using which you can add custom validations. To add this validation you have to add following lines of code inside your current active theme’s functions.php

add_filter( 'gform_field_validation_9_57', 'gf_custom_validation', 10, 4 );
function gf_custom_validation( $result, $value, $form, $field ) {
  
       // Only for Single Line Text or Paragraph fields.
    if ( $field->type == 'textarea' ) {
 
        $less = false;
        $message='';
        $word_count=str_word_count($value, 0);
        if($value != strip_tags($value)){
            // is HTML
            $less = true;
            $message='HTML tags not allowed!';
           }else{
           
            if($word_count<200){
                $less=true;
                $message='Sorry, Minimum 200 words required!';
            }
            elseif( $word_count>500)
            {
                $less = true;
                $message='Sorry, Maximum 500 words allowed!';
            }
            else{
                $less = false;
            }
        }
        

      if ( true === $less ) {
            $result['is_valid'] = false;
            $result['message']  = empty( $field->errorMessage ) ? $message.' ( You added: '.$word_count.' words. )' : $field->errorMessage;
      }
    }
 
    return $result;
}

You have to add your form ID and field id inside the above code. You have to change below line with your form ID and field id. 9 is the form ID and 57 is field ID. Replace that with your form id and field id.

add_filter( 'gform_field_validation_9_57', 'gf_custom_validation', 10, 4 );

Leave a Reply

Your email address will not be published. Required fields are marked *