I found some older posts on the subject and I was not able to come up with anything that works for me. I have a site with multiple forms. I tried using a few different snippets I found. Some of them just plain caused critical errors that I had to roll back. I did find this one that didn’t break the site but doesn’t work properly.
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;
}
When I use this it throws the hyperlink error when using an email address on some forms and a “There has been a critical error on this website.” on others.
Is there an updated snippet I can take advantage of? Getting spammed like mad.
If you want to remove text links only you can use the following snippet.
// Change the field type from text to the correct field type or simply do not specify the field type for this to run for all fields.
if ( $field->type == 'text' ) {
$nourl_pattern = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
$value = preg_replace($nourl_pattern, ' ', $value);
}
If you want to strip and remove both the text versions of the URLs e.g. https://website.com and hyperlinks e.g. Link you can use the following snippet.
// This will remove all hypertext links and regular string links
// Change the field type from text to the correct field type or simply do not specify the field type for this to run for all fields.
if ( $field->type == 'text' ) {
$nourl_pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
$replacement = "";
$value = preg_replace($nourl_pattern, $replacement, $value); // update value
}
If you simply want to return instead of accepting the submissions with sanitized values, I would use the below snippet. Here, I just updated the Regular Expression. It will detect string links as well as hypertext links that contain <a> tags
add_filter( 'gform_field_validation', 'high_gf_validation', 10, 4 );
function high_gf_validation( $result, $value, $form, $field ) {
$nourl_pattern = '/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/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;
}