我知道这可能会被认为是离题的,但我不确定还能在哪里发布这篇文章,因为它也涉及WordPress以及插件联系人表单7。如果你知道我应该把这个贴在哪里而不是这里,请告诉我。
我希望有一个有条件的必填字段。我已经找到了可以使用的代码,但我觉得我自己很困惑,需要一些外部视角。
我需要做的是,如果我的复选框被选中为“是”,它将使其旁边的下拉列表成为必需的,如果复选框被选中为“否”,则不需要。
这是我的表单,在后端有短代码:
If you have ordered from us in the past, do you already work with one of our outside sales representatives?
[checkbox* check-sales id:checksales "Yes" "No"]
If you checked "Yes" which representative do you generally deal with?
[select sales-rep id:sales include_blank "Marla" "Lisa" "Wendy" "Stacy" "Nicole" "Linda" "Jody" "Gisele" "Ray" "Craig"]
[submit]
下面是进入函数的php代码示例。php文件。
function is_gmail($email) {
if(substr($email, -10) == \'@gmail.com\') {
return true;
} else {
return false;
};
};
function custom_email_validation_filter($result, $tag) {
$type = $tag[\'type\'];
$name = $tag[\'name\'];
if($name == \'your-email\') { // Only apply to fields with the form field name of "your-email"
$the_value = $_POST[$name];
if(!is_gmail($the_value)){
$result[\'valid\'] = false;
$result[\'reason\'][$name] = \'This is not a gmail address!\'; // Error message
};
};
return $result;
};
add_filter(\'wpcf7_validate_email\',\'custom_email_validation_filter\', 10, 2); // Email field
add_filter(\'wpcf7_validate_email*\', \'custom_email_validation_filter\', 10, 2); // Required Email field
我知道这是为了检查电子邮件。然而,我让自己困惑的是,为了使复选框和下拉列表能够工作,我需要更改什么。
SO网友:Muhammad Russell
这个解决方案对我有效。在我的情况下,如果选中复选框,则需要地址。
function my_custom_conditional_required($result, $tag) {
$tag = new WPCF7_Shortcode( $tag );
$name = $tag->name;
$value = isset( $_POST[$name] )
? trim( wp_unslash( strtr( (string) $_POST[$name], "\\n", " " ) ) )
: \'\';
$myCheckbox= $_POST[\'myCheckbox\'][0];
if( $name == "address" && $myCheckbox== true){
if ( \'\' == $value ) :
$result->invalidate( $tag, \'Address is required.\' );
endif;
}
return $result;
}
add_filter( \'wpcf7_validate_text\', \'my_custom_conditional_required\', 10, 2 );
add_filter( \'wpcf7_validate_text*\', \'my_custom_conditional_required\', 10, 2 );