skip to Main Content

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;
}

2

Answers


  1. 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." );
    }
    
    Login or Signup to reply.
  2. 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 i f 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search