Word Limits for Gravity Forms Paragraph Fields
Lets you require a minimum and maximum number of words in Gravity Forms paragraph fields, for essays, applications and testimonials.
Opens WPIDE on
Code
add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
if ( 'textarea' !== $field->type || ! $result['is_valid'] || ! preg_match( '/\bwords-(\d+)-(\d+)\b/', (string) $field->cssClass, $m ) ) {
return $result;
}
$text = trim( wp_strip_all_tags( (string) $value ) );
if ( '' === $text && ! $field->isRequired ) {
return $result;
}
$words = preg_match_all( '/[\p{L}\p{N}\']+/u', $text );
$min = (int) $m[1];
$max = (int) $m[2];
if ( $words < $min ) {
$result = array( 'is_valid' => false, 'message' => sprintf( 'Please write at least %1$d words (currently %2$d).', $min, $words ) );
} elseif ( $max > 0 && $words > $max ) {
$result = array( 'is_valid' => false, 'message' => sprintf( 'Please keep it under %1$d words (currently %2$d).', $max, $words ) );
}
return $result;
}, 10, 4 );
Notes
Add a CSS class such as words-50-300 to a paragraph field to require 50 to 300 words; use words-50-0 for a minimum only.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.