How to Block Links (URLs) in Text Area | Regex Format [RESOLVED]

Good Day,

We are using the code snippet provided here to block links (URLs) entered into our gravity forms text area.

It works great, but does not block all possible URL patterns, so we’re using the following, modified version:

Note: We updated the code lines $nourl_pattern = and $result[‘message’] =.

/* Block URLs in Text Area */
 
>add_filter( 'gform_field_validation_1_5', 'validate_input_1_5', 10, 4 );
      function validate_input_1_5( $result, $value, $form, $field ) {
      $nourl_pattern = '(ftp|http|https|www|.com|.net|.org|.io|.biz|.info|.mil|.edu|.gov|.me|.int|FTP|HTTP|HTTPS|WWW|.COM|.NET|.ORG|.IO|.BIZ|.INFO|.MIL|.EDU|.GOV|.ME|.INT)';    
      if ( preg_match( $nourl_pattern, $value ) ) {    
      $result['is_valid'] = false;    
      $result['message']  = 'Your message cannot contain hyperlinks.';
      } 
 return $result;
}

The above prompts the following question:

Is there a way we can further modify the above code snippet to capture all possible URLs patterns using Regex? The code snippet provided here does not work (for us, at least).

Thank you!

Solved:

The code snippet (regex format) provided below blocks URLs with/without FTP/HTTP/HTTPS and with/without WWW. It also blocks standalone URLs or URLs inserted in a sentence.

Important: Don’t forget to adjust the noted field IDs and message to suit your needs.

Enjoy! :slight_smile:


Code Snippet:

/* Block URLs in Text Area */

add_filter( ‘gform_field_validation_1_5’, ‘validate_input_1_5’, 10, 4 );
     function validate_input_1_5( $result, $value, $form, $field ) {
     $nourl_pattern = '/\b(?:(?:https?|ftp|http):\/\/)?(?:[\w-]+\.)+([a-z]|[A-Z]|[0-9]){2,24}$/i'; // Regex Pattern (Detects URLs with or without HTTP/WWW)
     if ( preg_match( $nourl_pattern, $value ) ) {
     $result[‘is_valid’] = false;
     $result[‘message’] = ‘Your message cannot contain hyperlinks.’;
     }
return $result;
}
1 Like