How to Block Link Tags and URLs (HyperLinks) Contained in Any Form Field | Regex Format [RESOLVED]

Good News!

After thorough testing, the code snippet provided below accomplishes the following:

  1. Detects and blocks Link Tags contained in any form field.
  2. Detects and blocks URLs (hyperlinks) contained in any form field.
  3. Detects and blocks URLs with/without HTTP/HTTPs and with/without WWW.
  4. Detects and blocks standalone URLs or URLs that are part of a sentence.
  5. Works for websites that contain multiple gravity forms.

Caution: If any of your forms contain a form field that is requesting a URL from your visitors, you will need to modify the code snippet provided below or use the one provided here.

Give it a spin. Hope this helps someone out there. :slight_smile:

Cheerio!


Code Snippet:

/* This Prevents Link Tags from Being Added to Form Fields */

add_filter( 'gform_allowable_tags', 'high_allowed_tags' );
	function high_allowed_tags( $allowable_tags ) {
	return '<p><strong><em>'; // No Link Tags Allowed (Only paragraph, strong, and emphasis or italic HTML tags are allowed)
}

/* This Prevents URLs from Being Added to Form Fields */

add_filter( 'gform_field_validation', 'high_gf_validation', 10, 4 );
	function high_gf_validation( $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