Gform_field_validation Prohibit Spaces or Special Characters from Field [RESOLVED]

Does anyone have a snippet to prohibit spaces and special characters from the name field?

Hello. If you want to allow only A-Z and a-z in a single line text field, you can use this code:

// apply only to field 3 in form 12
add_filter( 'gform_field_validation_12_3', 'character_validation', 10, 4 );
function character_validation( $result, $value, $form, $field ) {

        // Check if value contains only letters (A-Z and a-z)
        if ( ! preg_match( '/^[A-Za-z]+$/', $value ) ) {
            $result['is_valid'] = false;
            $result['message'] = 'Please enter only letters (A-Z).';
        }

    return $result;
}

You will need to change the field ID from 3 to your field ID and change 12 to your form ID. If you are using an actual name field, that has two parts and you would need to change the code to handle that. Let us know if that is the case.

This will allow only A-Z and a-z, no other characters, including spaces. If you have different requirements, the regex will need to be updated. Please let us know if you need to allow more than just A-Z in upper and lower case. Thank you.

2 Likes

Thank you!!

Yes. Can you please assist for the first middle and last name fields? I think we use something like 120.3 120.4 120.6

That’s super helpful. Can you please provide the code for the First, Middle, Last Name fields? That’s where we need to validate.

Thank you!

We’ll need to see your form to get the field IDs. Can you share that file somewhere and share the link here or via PM (if you click my name you can send a private message.) Thank you.

It’s form ID 21 fields 126.3 126.4. 126.6

Thank you

Hello J. This should take care of that:

// form 21, field 126
add_filter( 'gform_field_validation_21_126', 'character_validation', 10, 4 );
function character_validation( $result, $value, $form, $field ) {
	
	// combine all three parts of the name field into one string for easy comparison
	$all_names = implode( $value );
	GFCommon::log_debug( __METHOD__ . '(): ALL NAMES => ' . print_r( $all_names, true ) );
	
	// Check if value contains only letters (A-Z and a-z)
	if ( ! preg_match( '/^[A-Za-z]+$/', $all_names ) ) {
		$result['is_valid'] = false;
		$result['message'] = 'Please enter only letters (A-Z).';
	}

	return $result;
}

If you have any questions, please let us know.

Thank you so much for this information. It works GREAT and I’m hoping that you would be so kind as to make ONE update to this. Because it is a name field, we DO want to allow for the “-” or hyphen for the last name. Are you able to show me how to update this line also allow for the - ?

if ( ! preg_match( ‘/[1]+$/’, $all_names ) ) {

Thank you!
J


  1. A-Za-z ↩︎

Change it to this:

if ( ! preg_match( '/^[A-Za-z\-]+$/', $all_names ) ) {

Thank you SO much! Works Great!