You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress Gravity Forms校验邮箱与当前用户邮箱匹配问题

问题描述

在WordPress中使用Gravity Forms插件时,需要校验email类型input字段的输入值是否与当前登录用户的邮箱地址匹配。现有实现存在异常:当该字段设置CSS visibility属性为hidden时,校验逻辑不会生效,用户可将默认填充的当前用户邮箱修改为任意值后成功提交表单,除该问题外其余表单功能运行正常。
原有实现代码如下:

add_filter( 'gform_field_validation_13_24', 'check_current_email', 10, 4 );
function check_current_email( $result, $value, $form, $field ) {
    if ( $field->type === 'email' ) {
        $user = wp_get_current_user();
  
        if ( empty( $value ) || ! email_exists( $value, $user->data->user_email, $user->ID ) ) {
            $result['is_valid'] = false;
            $result['message']  = 'Incorrect current user email. Please try again.';
        }
    }
  
    return $result;
}
故障原因
  • 核心问题是email_exists()函数调用错误:WordPress原生email_exists()仅接受1个待查询的邮箱字符串参数,返回值为该邮箱对应的用户ID(邮箱存在)或false(邮箱不存在),原代码传入的第二、第三个参数会被直接忽略,根本没有实现「输入值与当前用户邮箱匹配」的校验逻辑,只是在检查输入的邮箱是否在站点存在。
  • 仅靠CSS设置visibility: hidden只是视觉上隐藏字段,Gravity Forms的前端校验脚本会跳过不可见字段的校验,用户可通过浏览器开发者工具随意修改字段值,此时如果服务端校验逻辑错误,篡改后的值就会直接通过提交。
修复方案

替换原有代码为以下服务端校验逻辑,该逻辑不受前端字段可见性影响,无论字段是否被CSS隐藏、是否被用户篡改,都会在提交时强制校验:

add_filter( 'gform_field_validation_13_24', 'check_current_email', 10, 4 );
function check_current_email( $result, $value, $form, $field ) {
    if ( $field->type !== 'email' ) {
        return $result;
    }

    $current_user = wp_get_current_user();
    // 未登录用户直接拦截
    if ( ! $current_user->exists() ) {
        $result['is_valid'] = false;
        $result['message']  = '请先登录后提交表单';
        return $result;
    }

    // 格式化输入值,邮箱不区分大小写统一转小写对比
    $input_email = sanitize_email( trim( $value ) );
    $correct_email = strtolower( $current_user->user_email );

    if ( empty( $input_email ) || strtolower( $input_email ) !== $correct_email ) {
        $result['is_valid'] = false;
        $result['message']  = '输入的邮箱与当前账户绑定邮箱不一致,请重试。';
    }

    return $result;
}

额外优化建议

  • 如果不需要用户看到该邮箱字段,不要仅通过CSS设置visibility: hidden实现隐藏,可直接在Gravity Forms的字段设置中,将可见性选项设置为「隐藏」,插件会自动将字段渲染为隐藏域,既不会在前端显示,也能正常提交和触发校验。
  • 不要依赖任何前端校验逻辑做权限类判断,所有涉及用户身份、权限的校验必须在服务端完成,避免用户通过篡改前端参数绕过限制。

内容的提问来源于stack exchange,提问作者Rajon Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:42:18