Filtering a specific field [RESOLVED]

In the id_1 form, I would like to check in the id_1 (text input) field if someone entered the numbers - if so - to block the form from being sent. It’s a first name field, but standard filtering (mask or regex) can’t handle the examples
Paweł and Ewa
Paul
(two names are okay, names can contain special characters (for a given language) - the only idea is to check if there is a digit or number in this field and display an error.

I tried with a filter like this:

add_filter ('gform_field_validation', function ($ result, $ value, $ form, $ field) {
    if ($ field-> type == 'name') {

        // Input values
        $ fullName = rgar ($ value, $ field-> id. '.3');
         
        if (empty ($ fullName)) {
            $ result ['is_valid'] = false;
            $ result ['message'] = empty ($ field-> errorMessage)? __ ('This field is required. Please enter a complete name.', 'Gravityforms'): $ field-> errorMessage;
        } else if (preg_match ('/ [A-Za-z]. * [0-9] | [0-9]. * [A-Za-z] /', $ fullName)) {// check for letters only
            $ result ['is_valid'] = false;
            $ result ['message'] = empty ($ field-> errorMessage)? __ ('Full name must ony contains letters.', 'Gravityforms'): $ field-> errorMessage;
        } else {
            $ result ['is_valid'] = true;
            $ result ['message'] = '';
        }
    }
    return $ result; // return results
}, 10, 4);

but it does not work reliably for special characters (like ą, ć, ż, ć, ü, ö, ä or other specific to different languages)

How to do it?

Try this one:

add_filter( 'gform_field_validation', 'gf_validate_name', 10, 4 );
function gf_validate_name( $result, $value, $form, $field ) {
	if ( $field->type != 'name' ) {
		return $result;
	}
	GFCommon::log_debug( __METHOD__ . '(): Name values => ' . print_r( $value, true ) );

	if ( $result['is_valid'] ) {
		foreach ( $value as $input ) {
			if ( ! empty ( $input ) && ! preg_match( '/^[\p{L} ]+$/u', $input ) ) {
				$result['is_valid'] = false;
				$result['message'] = 'Only letters!';
			}
		}
	}
	return $result;
}

No need to use form or field id’s, it will target any Name field.

1 Like

Thank you very much, and how to modify it so that it works only on a specific field of a specific form (form id: 1 input id: 1)

If you check the filter usage documentation here, you will find that you can easily limit the snippet scope by adding the form and field id to the filter name.

So if you want to limit it to form 1 and field 1, change this line

add_filter( 'gform_field_validation', 'gf_validate_name', 10, 4 );

To this

add_filter( 'gform_field_validation_1_1', 'gf_validate_name', 10, 4 );

Hi.
In order to use the code above to avoid the commas or semi-colons in a Single Text Field, what would need to be changed?

Hi Eduardo. Please open a new topic with your request in detail. Thank you.