• How? Validate checkboxes with CF7

    I have this code

    function cf7_length_validation_filter( $result, $tag ) {
    	$name = $tag['name'];
    	$value = isset( $_POST[$name] ) ? trim( $_POST[$name] ) : '';
    	$minLen = 0;
    	
    	// Empty Fields
    	if( empty( $value ) || strlen( $value ) == 0 ) {
    		$result->invalidate( $tag, "Field cannot be empty." );
    	}
    	
    	// Field Length
    	switch ( $name ) {
    		case 'fname':
    		case 'lname':
    			$minLen = 2;
    			break;
    		case 'email':
    			$minLen = 6;
    			break;
    	}
    	
    	if ( empty( $value ) || strlen( $value ) < $minLen ) {
    		$result->invalidate( $tag, "This field is too short." );
    	}
    
    
    	return $result;
    }

    It works for those fields. For checkbox, it ALWAYS says Field cannot be empty

    add_filter( ‘wpcf7_validate_checkbox*’, ‘cf7_length_validation_filter’, 5, 2 );

    without this line, no validation happens at all

    • This topic was modified 1 year, 7 months ago by mayy3321.
Viewing 1 replies (of 1 total)
  • That’s because what’s in _POST is an array, not a scalar.

    Despite this forum’s formatting, I corrected the version below. You’ll need to change the ‘fname’ etc.

    For anyone chancing on this, I’m available to fix issues like this on a paid basis.

    function cf7_length_validation_filter( $result, $tag ) {
    $name = $tag[‘name’];
    $value = !empty( $_POST[$name] ) && is_array( $_POST[$name] ) ? trim( reset( $_POST[$name] ) ) : array();
    $minLen = 0;
    rawdebug(‘call’, $name, $_POST, $value);

    // Empty Fields
    if( !$value ) {
        $result->invalidate( $tag, "Field cannot be empty." );
    }
    
    // Field Length
    switch ( $name ) {
        case 'fname':
        case 'lname':
            $minLen = 2;
            break;
        case 'email':
            $minLen = 6;
            break;
    }
    
    if ( empty( $value ) || strlen( $value ) < $minLen ) {
        $result->invalidate( $tag, "This field is too short." );
    }
    
    
    return $result;

    }

Viewing 1 replies (of 1 total)
  • The topic ‘Validate checkboxes with CF7’ is closed to new replies.