• Hello! I’m trying to check if a field is empty to add in a custom error message.

    Here is the strange part and I don’t know what I’m missing. For a test, I did a simple form.

    <label> Your name
        [text* your-name] </label>
    
    <label> Your message (optional)
        [textarea* your-message] </label>
    
    [submit "Submit"]

    If I check if your-name field is NOT empty, this code works great.

    add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 20, 2);
    
    function custom_text_validation_filter($result, $tag) {
    	
    	if ('your-name' == $tag->name) {
    		$field_name = isset( $_POST['your-name'] ) ? trim( $_POST['your-name'] ) : '';
    		
    		if ($field_name !== '') {
    			 $result->invalidate( $tag, "Are you sure this is the correct name?" );
    		}
    	}
    
        return $result;
    }

    As you see, I’m checking if field_name is NOT empty.
    BUT, if I change that to check if the field IS empty, the form just displays the generic “Please fill out this field text”.

    add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 20, 2);
    
    function custom_text_validation_filter($result, $tag) {
    	
    	if ('your-name' == $tag->name) {
    		$field_name = isset( $_POST['your-name'] ) ? trim( $_POST['your-name'] ) : '';
    		
    		if ($field_name == '') {
    			 $result->invalidate( $tag, "Are you sure this is the correct name?" );
    		}
    	}
    
        return $result;
    }

    I’m unsure why checking if its not empty is working correctly but changing it to check if it IS empty is not working.

    Anyone see what I could be doing wrong?

Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Checking if field is empty not working’ is closed to new replies.