I would like to be able to send emails from a CF7 form to more than one recipient using an input field in the form to obtain the email addresses. The problem is that the email field of CF7 only validates a single email address not two separated by comma, which are considered invalid.
I COULD use a text field, but then there is no validation at all of correct email syntax. How could I add a field type "emails" with validation of single or multiple emails?
The easiest way to achieve this is to use a std text field and create your own validation. You need to hook the cf7 plugin's validation filter for text fields,
add_filter( 'wpcf7_validate_text*', 'my_vaidated_list_of_emails', 10, 2 );
add_filter( 'wpcf7_validate_text', 'my_vaidated_list_of_emails', 10, 2 );
function my_vaidated_list_of_emails( $results, $field_tag ) {
// check this is your field
if ( 'email_lists' === $field_tag->name && isset( $_POST['email_lists'] ) ) {
// split the lists into an array of emails
$emails = explode( ',', $_POST['email_lists'] );
$count = 0;
foreach ( $emails as $e ) {
$count++;
if ( false === filter_var( strtolower( trim($e) ), FILTER_VALIDATE_EMAIL ) ) {
$results->invalidate( $tag, "Email no.{$count} in your list is invalid." );
break; // from the loop, no need to go any further.
}
}
}
return $results;
}
Note: I haven't tested this, but this should do it.
Edit: changed the code to use the far simpler filter_var as suggested by andrew in the comments below.