Powered By Blogger

Wednesday, October 12, 2016

Custom validation in contact form 7

function.php :


/** text validation for contact form 7 **/
add_filter( 'wpcf7_validate_text*', 'custom_text_confirmation_validation_filter', 20, 2 );

function custom_text_confirmation_validation_filter( $result, $tag ) {
    $tag = new WPCF7_Shortcode( $tag );

    if ( 'your-name' == $tag->name ) {
        $your_name = isset( $_POST['your-name'] ) ? trim( $_POST['your-name'] ) : '';
//remove space from string
$trim_name = str_replace(' ', '', $your_name);
//special char validation
        if ( $your_name ) {
if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $your_name) || ! ctype_alpha($trim_name) )
{
   $result->invalidate( $tag, "Name seems invalid." );
}          
        }
    }

    return $result;
}

/** URL validation for contact form 7 **/
function cf7_custom_url_check( $result, $url )
{
  if ($result)
  {
    $regex='@^(https?\://)?(www\.)?([a-z0-9]([a-z0-9]|(\-[a-z0-9]))*\.)+[a-z]+$@i';
    if (!preg_match($regex,$url)) $result=FALSE;
  }
  return $result;
}
add_filter( 'wpcf7_is_url', 'cf7_custom_url_check', 10, 2 );

No comments:

Post a Comment