WordPress Contact Form 7 create a custom URL validation

In WP the Contact Form 7 is one of the most popular plugins for creating contact forms. One thing that you might have noticed though is that the validation of the URL field will not fail when you expect them to fail. For example, with the URL value of http://ikodes.com, the plugin will consider this as a valid URL, even though, the URL value is missing top level domain part. The solution to this problem is to have a custom validation for the URL field. This article will show you how to achieve that.

Adding our own URL validation using wpcf7_is_url filter

Our custom URL validation will be fairly simple. If the default URL validation of the plugin is valid, we do one additional validation using a regex expression that will try to validate a domain name. There are many regular expressions on the internet for domain name validation, the one I use in the code below seems to work pretty well. If regex validation fails, then we set $result to FALSE, which will signal the plugin to display “URL seems invalid.” error message.

In the functions.php of your theme, add the following code:

function ikodes_contact7_check( $result, $url )
{
  if ($result)
  {
    $regex='@^(https?\://)?(www\.)?([a-z0-9]([a-z0-9]|(\-[a-z0-9]))*\.)+[a-z][email protected]';
    if (!preg_match($regex,$url)) $result=FALSE;
  }
  return $result;
}
add_filter( 'wpcf7_is_url', 'ikodes_contact7_check', 10, 2 );

 

Related posts