dongsi073898 2018-01-09 11:44
浏览 34
已采纳

重力形式单行文本字段自定义验证(数字只有10位或更多位)

Our web form built with Gravity Forms on WordPress uses a "single line text" field type for the phone number field.

How can I add a custom validation to this so that it will only allow submission of integers and only if there is 10 or more input?

This is because in Australia our phone numbers (without country code) are 10 digits. We're currently getting responses containing letters or incomplete numbers.

I've just implemented the below function but it doesn't work.

// Form Phone Field Validation to use numbers only with minimum 10 digits
add_filter( 'gform_field_validation_16_4', 'custom_validation', 10, 4 ); //Replace the ## with your form ID
function custom_validation( $result, $value, $form, $field ) {

$value = str_replace(array('(',')','-',' '),'',$value);//Remove hyphens, parenthesis, and spaces - you can take this out if you want strict numbers only

if ( $result['is_valid'] && strlen( $value ) < 10 && is_numeric( $value ) ) { 

$result['is_valid'] = false;
$result['message'] = 'Please enter a valid phone number of 10 or more digits with area code';
}
return $result;
}
  • 写回答

2条回答 默认 最新

  • drwj4061 2018-01-09 13:39
    关注

    Based on documentation

    you should be doing something like this,

    //replace {FORM_ID} with your form ID
    add_filter( 'gform_validation_{FORM_ID}', 'custom_validation' );
    function custom_validation( $response ) {
        $form = $response['form'];
    
    
        //replace {INPUT_ID} with the input ID you want to validate    
        $value = str_replace(array('(',')','-',' '), '', rgpost( 'input_{INPUT_ID}' ) );
    
        if ( strlen( $value ) < 10 || !is_numeric( $value ) ) { 
    
            $response['is_valid'] = false;
    
            //finding Field with ID and marking it as failed validation
            foreach( $form['fields'] as &$field ) {
    
                //NOTE: replace {INPUT_ID} with the field you would like to validate
                if ( $field->id == '{INPUT_ID}' ) {
                    $field->failed_validation = true;
                    $field->validation_message = 'Please enter a valid phone number of 10 or more digits with area code';
                    break;
                }
            }
    
        }
    
        //Assign modified $form object back to the validation result
        $response['form'] = $form;
        return $response;
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。
  • ¥30 求给定范围的全体素数p的(p-2)/p的连乘积值
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗