Created
September 11, 2026 12:09
-
-
Save mwhiteley16/f8e03d0fad2cbcc63f3f2050768acb1a to your computer and use it in GitHub Desktop.
Gravity Forms Custom Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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