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

如何在Elementor表单中实现邮政编码验证及服务区校验

Elementor表单邮政编码验证实现

以下代码可实现Elementor Pro表单的邮政编码字段验证,当邮编格式无效或不在服务范围内时,返回对应的错误提示:

function elementor_form_zip_code_field_validation( $field, $record, $ajax_handler ) {
    // 仅针对名为zip_code的字段执行验证
    if ( $field['name'] !== 'zip_code' ) {
        return;
    }

    $zip_code = trim( $field['value'] );

    // 步骤1:验证是否为有效的5位数字格式
    if ( ! preg_match( '/^\d{5}$/', $zip_code ) ) {
        $ajax_handler->add_error(
            $field['id'],
            esc_html__( '邮政编码必须是正好5位数字(例如:12345)。', 'textdomain' )
        );
        return;
    }

    // 步骤2:验证邮编是否在服务范围内
    $allowed_zips = [ '90210', '32810', '10001' ];

    if ( ! in_array( $zip_code, $allowed_zips, true ) ) {
        $ajax_handler->add_error(
            $field['id'],
            esc_html__( '当前我们暂未覆盖您所在区域的服务,请后续关注。', 'textdomain' )
        );
        return;
    }
}
add_action( 'elementor_pro/forms/validation/zip_code', 'elementor_form_zip_code_field_validation', 10, 3 );

代码说明:

  • 钩子绑定:通过elementor_pro/forms/validation/zip_code动作钩子,指定仅对表单中name为zip_code的字段执行验证逻辑
  • 格式校验:使用正则表达式/^\d{5}$/确保输入是纯5位数字,排除非数字、位数不符的情况
  • 服务范围校验:预先定义允许的邮编数组$allowed_zips,判断用户输入的邮编是否在服务覆盖范围内
  • 错误提示:通过$ajax_handler->add_error()方法,给对应字段添加本地化的错误提示,确保前端能正确显示验证失败信息

内容的提问来源于stack exchange,提问作者Dutchess Dad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:09:55