• Resolved tiitus

    (@tiitus)


    Hello,

    I found this fab code on doing conditional required fields with a filter, without a plugin. However it is not working, and the form submits without the required fields. I am trying to make 2 fields required if a checkbox is checked, the “fromwho” and “friend-email”
    fields named respectively. I have also been trying to follow this example from https://contactform7.com/2015/03/28/custom-validation/

    add_filter( 'wpcf7_validate_text', 'my_conditional_required', 10, 2 );
    add_filter( 'wpcf7_validate_text*', 'my_conditional_required', 10, 2 );
    add_filter( 'wpcf7_validate_email', 'my_conditional_required', 10, 2 );
    add_filter( 'wpcf7_validate_email*', 'my_conditional_required', 10, 2 );
    
    function my_conditional_required($result, $tag) {
        $tag = new WPCF7_Shortcode( $tag );
        $name = $tag->name;
    
        $value = isset( $_POST[$name] )
            ? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
            : '';
    		
    	if ( "fromwho" == $name && 'true' == $_POST['checkboxA'][0] ) :
            if ( '' == $value  ) :
                $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
            endif;
        endif;
    	
    	if ( 'friend-email' == $name && 'true' == $_POST['checkboxA'][0] ) :
    		if ( '' == $value ) :
    			$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
    		endif;
    	endif;
    
        return $result;
    }

    Any help appreciated!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Takayuki Miyoshi

    (@takayukister)

    Can I see the site?

    Thread Starter tiitus

    (@tiitus)

    Hello Takayuki,

    After some fiddling I actually remembered that my checkbox value is not true/false(oopsies). So I was just using the wrong value. Seems to be working correctly now that I got the checkbox value I was looking for.
    Great snippet of code (and even nicer with the custom validations provided by Contact Form 7)

    🙂

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Conditional required field without the plugin’ is closed to new replies.