How to block links in text field? [RESOLVED]

I’m trying to prevent people from entering URLs into a text field. I have this in my functions.php but it seems to break the form:

function no_url_regex() {
return '(http|https)';
}

// add custom validation to form
add_filter( 'gform_field_validation_1', 'validate_phone_1', 10, 4 );
function validate_phone_1( $result, $value, $form, $field ) {
$nourl_pattern = no_url_regex();
if ( !preg_match( $nourl_pattern, $value ) ) {
    $result['is_valid'] = false;
    $result['message']  = 'Message can not contain website addresses.';
}

return $result;
}

Hi Mark. Your no_url_regex function is not actually returning true or false, it’s returning “(http|https)”. In that function you will need to implement some sort of checking to see if a link was submitted.

Hi Chris. I thought the true/false comes from the IF statement that contains the preg_match?

Btw, thanks for helping me out.

I don’t think so. Using a separate function like that should return a true or false, so you can determine if the field fails validation or not.

What exactly are you trying to prevent submission of? Strings beginning with https or http only?

This looks like it should be close, but it appears that the code you have above would currently flag values that don’t match. If you want to flag values that do match your pattern (that being returend by your no_url_regex function), then the if statement should read…

if ( preg_match( $nourl_pattern, $value ) ) {

You’ll probably also want to do an initial check against the field type, so that you’re only applying to text fields. Something like…

if ( $field->type == 'text' ) {

Guys, thanks for your help! Here is the code that worked:

// add custom validation to form
add_filter( 'gform_field_validation_74_7', 'validate_phone_74_7', 10, 4 );
function validate_phone_74_7( $result, $value, $form, $field ) {
    $nourl_pattern = '(http|https)';
    if ( preg_match( $nourl_pattern, $value ) ) {
    $result['is_valid'] = false;
    $result['message']  = 'Message can not contain website addresses.';
}
return $result;
}
2 Likes

Thanks for the update Mark.