我们在WordPress上使用Gravity Forms构建的网络表单使用电话号码字段的“单行文字”字段类型。
如何为此添加自定义验证,以便它只允许提交整数,并且仅当有10个或更多输入时?
这是因为在澳大利亚,我们的电话号码(没有国家代码)是10位数。我们目前正在收到包含字母或不完整数字的回复。
我刚刚实现了以下功能,但它不起作用。
// 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;
}
答案 0 :(得分:1)
你应该做这样的事情,
//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 :(得分:0)
尝试使用“gform_validation”函数添加过滤器:
add_filter( 'gform_validation', 'custom_validation' );
function custom_validation( $validation_result ) {
//your code here
}