Contact Form 7 email validation regex. We can check characters and domain names by regex.
Please check the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
add_filter( 'wpcf7_validate_email', 'wpcf7_custom_email_validation_filter', 10, 2 ); add_filter( 'wpcf7_validate_email*', 'wpcf7_custom_email_validation_filter', 10, 2 ); function wpcf7_custom_email_validation_filter( $result, $tag ) { $name = $tag->name; $email = isset( $_POST[$name] ) ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) ) : ''; // Split out the local and domain parts. list( $local, $domain ) = explode( '@', $email, 2 ); // LOCAL PART // Test for invalid characters. if ( ! preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) { /** This filter is documented in wp-includes/formatting.php */ return $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ) );; } // DOMAIN PART // Test for sequences of periods. if ( preg_match( '/\.{2,}/', $domain ) ) { return $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ) ); } return $result; } |
YouTube – Watch Now
How to block some domain names for email input?
We can use wpcf7_validate_email
filter to validate the email address. This will block all email address that exists with yahoo.com
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
add_filter( 'wpcf7_validate_email', 'wpcf7_custom_email_validation_filter', 10, 2 ); add_filter( 'wpcf7_validate_email*', 'wpcf7_custom_email_validation_filter', 10, 2 ); function wpcf7_custom_email_validation_filter( $result, $tag ) { $name = $tag->name; $email = isset( $_POST[$name] ) ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) ) : ''; // Split out the local and domain parts. list( $local, $domain ) = explode( '@', $email, 2 ); if ( $domain == 'yahoo.com' ) { return $result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ) ); } return $result; } |
Fake email provider domain names: https://gist.github.com/adamloving/4401361
How to change the error message for email errors?
1 2 3 4 5 6 7 8 9 |
add_filter( 'wpcf7_messages', 'my_email_error_messages', 10, 1 ); function my_email_error_messages( $messages ) { return array_merge( $messages, array( 'invalid_custom_email' => array( 'description' => __( "Some email discription", 'contact-form-7' ), 'default' => __( "Email error message here", 'contact-form-7' ), ), |
Now you can edit from wp-admin > contact form 7 > message section.
You need to add invalid_custom_email
in wpcf7_get_message
function.
Example
1 |
$result->invalidate( $tag, wpcf7_get_message( 'invalid_custom_email' ) ); |