我希望能够使用表单中的输入字段获取电子邮件地址,将电子邮件从 CF7 表单发送给多个收件人。问题是 CF7 的电子邮件字段仅验证单个电子邮件地址,而不验证用逗号分隔的两个电子邮件地址,这被认为是无效的。
我可以使用文本字段,但根本没有验证电子邮件语法是否正确。如何添加字段类型“电子邮件”并验证单个或多个电子邮件?
实现此目的的最简单方法是使用标准文本字段并创建您自己的验证。您需要为文本字段挂钩 cf7 插件的验证过滤器,
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' === $tag->name && ! isset( $_POST['email_lists'] ) ) {
// split the lists into an array of emails
$emails = explode( ',', $_POST['email_lists'] );
// match an email
$email_regex = '/^[_a-z0-9-+]+(\.[_a-z0-9-+]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i';
$count = 0;
foreach ( $emails as $e ) {
$count++;
if ( false === preg_match( $email_regex, strtolower( trim($e) ) ) ) {
$results->invalidate( $tag, "Email no.{$count} in your list is invalid." );
break; // from the loop, no need to go any further.
}
}
}
return $results;
}
注意:我还没有测试过这个,但这应该可以。