Skip to content

Instantly share code, notes, and snippets.

@mwhiteley16
Created September 11, 2026 12:09
Show Gist options
  • Select an option

  • Save mwhiteley16/f8e03d0fad2cbcc63f3f2050768acb1a to your computer and use it in GitHub Desktop.

Select an option

Save mwhiteley16/f8e03d0fad2cbcc63f3f2050768acb1a to your computer and use it in GitHub Desktop.
Gravity Forms Custom Validation
<php
/**
* Validate Gravity Forms text and name fields.
*
* Rejects common gibberish patterns, repeated characters, invalid characters,
* and values shorter than two characters.
*
* @since 1.6.2
*
* @param array $validation_result Gravity Forms validation result.
*
* @return array Modified Gravity Forms validation result.
*/
function wd_validate_gravity_form_fields( $validation_result ) {
$form = $validation_result['form'];
foreach ( $form['fields'] as &$field ) {
// Target single-line text and name fields.
if ( ! in_array( $field->type, array( 'text', 'name' ), true ) ) {
continue;
}
$value = rgpost( 'input_' . $field->id );
// Handle the array returned by a full name field.
if ( is_array( $value ) ) {
$value = implode( ' ', $value );
}
// Skip empty fields if they are not required.
if ( empty( $value ) ) {
continue;
}
// Block common keyboard-mashing and placeholder values.
$gibberish_patterns = '/(asdf|qwerty|zxcv|1234|test|null|n\/a)/i';
// Block four or more repeated consecutive characters.
$repeated_chars = '/(.)\1{3,}/i';
// Allow letters, whitespace, hyphens, and apostrophes only.
$invalid_chars = '/[^\p{L}\s\-\']/u';
// Require at least two characters.
$is_too_short = mb_strlen( trim( $value ) ) < 2;
if (
preg_match( $gibberish_patterns, $value ) ||
preg_match( $repeated_chars, $value ) ||
preg_match( $invalid_chars, $value ) ||
$is_too_short
) {
$validation_result['is_valid'] = false;
$field->failed_validation = true;
$field->validation_message = __(
'Please enter a valid name using letters, spaces, hyphens, or apostrophes.',
'text-domain'
);
}
}
$validation_result['form'] = $form;
return $validation_result;
}
add_filter( 'gform_validation', __NAMESPACE__ . '\wd_validate_gravity_form_fields' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment