Disable Special Characters but allow "Space"

So I want to disable special characters cause a 3rd party integration do not accept the special characters.

I have found this code below, but it also doesn’t allow space. So how do I edit the code below, so it allows spaces but just not special characters like ÆÅØ and so on.

add_filter( 'gform_field_validation', function( $result, $value, $form, $field ) {

   if ( strpos( $field->cssClass, 'require_alpha_num' ) !== false && ! ctype_alnum( $value ) ) {

      $result['is_valid'] = false;
      $result['message'] = 'Error: You are not allowed to use special characters';

   }

   return $result;

}, 10, 4 );

Try this modified code to allow uppercase and lowercase letters and spaces only:

add_filter( 'gform_field_validation', function( $result, $value, $form, $field ) {
	$pattern = "/^[a-zA-Z ]*$/"; // note the space before the closing brace
	if ( strpos( $field->cssClass, 'letters_spaces' ) !== false && ! preg_match( $pattern, $value ) ) {
		$result['is_valid'] = false;
		$result['message'] = 'Error: You are not allowed to use special characters';
	}
	return $result;
}, 10, 4 );

Note - I changed the CSS Class name to “letters_spaces” as well. Be sure you add that CSS Class name to the settings on the Appearance tab of the field you want to target with this validation.

Screenshot: Annotation on 2021-11-29 at 13-13-22.png - Droplr

Thank you Chris

That was a very fast response :smiley:

If I also want numbers to be allowed, how do I do that?

You did not mention numbers :slight_smile:

Change this line:

$pattern = "/^[a-zA-Z ]*$/";

To this:

$pattern = "/^[a-zA-Z0-9 ]*$/";

I know sorry

And thank you again Chris!

1 Like

Did that work for you? Let me know and I’ll mark this as resolved if so, or will give it another shot. Thank you.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.