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

WordPress Gravity Forms手机号字段自定义验证求助:仅允许10位以上整数

Fixing Gravity Forms Australian Phone Number Validation

Let's get your phone number validation working properly! The issue with your current code is a logic error in the condition check—you're only marking the field invalid when all three conditions are true, but we need to flag it if either the input isn't numeric OR it's too short.

Here's the corrected code:

// 表单手机号字段验证:仅允许10位及以上数字(澳洲本地手机号)
add_filter( 'gform_field_validation_16_4', 'custom_australian_phone_validation', 10, 4 );
// 16 = 表单ID,4 = 手机号字段ID,根据你的实际情况调整
function custom_australian_phone_validation( $result, $value, $form, $field ) {
    // 先清理输入:移除常见的格式符号(括号、空格、连字符)
    $cleaned_value = str_replace( array('(',')','-',' '), '', $value );

    // 核心验证逻辑:如果清理后的值不是纯数字,或者长度小于10位 → 验证失败
    if ( $result['is_valid'] && ( !is_numeric( $cleaned_value ) || strlen( $cleaned_value ) < 10 ) ) {
        $result['is_valid'] = false;
        $result['message'] = '请输入有效的澳大利亚手机号(不含国家码需为10位纯数字,可带格式符号)';
    }

    return $result;
}

What changed & why:

  • Renamed the function to something more descriptive (optional but good practice for maintainability)
  • Fixed the condition logic: Swapped && (AND) for || (OR) because we need to catch either non-numeric input or insufficient length. Your original code only triggered when the input was numeric AND too short—so non-numeric values slipped right through!
  • Clarified the error message to help users understand exactly what's required
  • Kept the input cleaning step, since Australian users often format numbers with spaces or brackets (e.g., 0412 345 678 or (04) 1234 5678)

Optional: Strict 10-digit validation

If you want to enforce exactly 10 digits (since Australian local numbers without country code are always 10 digits), tweak the length check to:

strlen( $cleaned_value ) != 10

How to implement:

  1. Copy this code into your theme's functions.php file, or use a custom code plugin like Code Snippets
  2. Double-check that the hook gform_field_validation_16_4 matches your actual form ID (16) and field ID (4)
  3. Test submitting the form with invalid inputs (letters, 9 digits, etc.) to confirm the validation triggers correctly

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:26:00