Validation - Letters, Numbers, Spaces and Hypens

Hi,

I am using the current code, but need to expand it out.

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'] = 'Please enter only numbers and letters';

   }

   return $result;

}, 10, 4 );

I want validation to be in place on all text fields, and for it to only allow letters, numbers, hypens (-) and spaces. Can anyone advise on what I would need to change please?

Thanks

Hi @browno
To allow hyphens (-) and spaces in the validation, you can use a regular expression (regex) to check for these characters in addition to letters and numbers. Here’s an example of how you can modify the code you provided:

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

   if ( strpos( $field->cssClass, 'require_alpha_num' ) !== false && ! preg_match( '/^[\p{L}\p{N}-\s]+$/u', $value ) ) {

      $result['is_valid'] = false;
      $result['message'] = 'Please enter only letters, numbers, hyphens, and spaces';

   }

   return $result;

}, 10, 4 );

This regex will allow any combination of letters (\p{L}), numbers (\p{N}), hyphens (-), and spaces. The u flag at the end of the regex ensures that the pattern is treated as a Unicode string, which allows the regex to match characters from different scripts and languages.

If you want to apply this validation to all text fields, you can remove the strpos check and simply return the modified $result in the function.

I hope this helps! Let me know if you have any questions or need further assistance.

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