Contact Form 7 默认提供多种用户输入验证,包括:

  • 是否填写了必填字段?
  • 电子邮件字段是否具有正确格式的电子邮件地址?
  • 上传的文件是否为可接受的文件类型和大小?

还可以添加自己的自定义验证:

以下例子演示如何实现自定义验证,让用户输入两次电子邮箱,验证两个电子邮箱是否一致,Contact Form 7 默认不支持电子邮件确认。

过滤字段

用于验证的过滤器钩子取决于 form-tag 的类型,wpcf7_validate_{form-tag}

假设您在表单中包含以下电子邮件字段:

Email:         [email* your-email]
Confirm email: [email* your-email-confirm]

以下代码显示了验证两个字段是否具有相同值

add_filter( 'wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2 );
 
function custom_email_confirmation_validation_filter( $result, $tag ) {
    if ( 'your-email-confirm' == $tag->name ) {
        $your_email = isset( $_POST['your-email'] ) ? trim( $_POST['your-email'] ) : '';
        $your_email_confirm = isset( $_POST['your-email-confirm'] ) ? trim( $_POST['your-email-confirm'] ) : '';
 
        if ( $your_email != $your_email_confirm ) {
            $result->invalidate( $tag, "Are you sure this is the correct address?" );
        }
    }
 
    return $result;
}

参考链接: