简体   繁体   中英

Custom Contact Form 7 Validation - One of two fields required

I have two text fields on my contact form: Cost Plus and Flat Rate. I need one of the two to be required. If cost-plus not entered, flat-rate is required.. and vice verse. This code in functions.php, doesn't seem to be giving me any feedback.

add_filter( 'wpcf7_validate_text', 'custom_form_validation_filter', 20, 2 );
  
function custom_form_validation_filter( $result, $tag ) {
    $tag = new WPCF7_FormTag($tag);
    
    if ('cost-plus' == $tag->name) {
        $cost_plus = isset($_POST['cost-plus']) ? trim($_POST['cost-plus']) : '';
        $flat_rate = isset($_POST['flate-rate']) ? trim($_POST['flate-rate']) : '';

        if ( empty($cost_plus) && empty($flat_rate) ) {
            $result->invalidate( $tag, "You must enter a Cost Plus OR Flat Rate value." );
        }
    }
  return $result;
}

The code below should work for your use-case. Perhaps you will need some extra checks dependent on what values are sent in the post request from the front-end. If the code below does not work for your use-case, please consider posting the entire POST request here for debugging purposes.

if(isset($_POST['cost-plus']) || isset($_POST['cost-plus'])){
    // Do logic here
}else{
    $result->invalidate( $tag, "You must enter a Cost Plus OR Flat Rate value." );
}

Don't know if I'm late but I managed to achieve this using 'wpcf7_validate' hook, looping through the tags in the form and checking if both of them are empty, and if they are I invalidate them like this:

/*
 * Contact Form 7 - Require the user to enter at least one phone contact or one mobile phone contact
 */
function requireAtLeastOneContact($result, $tags){
    $emptyContactTags = [];
    foreach ($tags as $tag) {
        if(($tag->name == 'telefone' && $_POST[$tag->name] == "") || ($tag->name == 'telemovel' && $_POST[$tag->name] == "")){
            $emptyContactTags [] = $tag;            
        }
    }    
    if(sizeof($emptyContactTags ) == 2){
        foreach ($emptyContactTags as $emptyContact) {
            $result->invalidate($emptyContact, "You must enter at least one contact.");
        }
    }
    return $result;
}

add_filter('wpcf7_validate', 'requireAtLeastOneContact', 20, 2);

Might need some improvement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM