phpwordpresscontact-form-7add-filter

How to validate zipcode in textfield of CF7


I have a textfield in CF7 which I want to validate if the users input is 4 digits and 2 characters, like: 1234AB (with no spaces and with capital letters).

This is what I have already, but it doesn't work:

function custom_postcode_validation_filter($result,$tag){

    $name = $tag->name;

    if($name == 'ba-postcode'){

        $bapostcode = $_POST['ba-postcode'];

        if($bapostcode != '') {

            if(!preg_match('/^([0-9]{4})\\([^a-Z]{2})$/', $bapostcode)) {

                $result->invalidate( $tag, "Vul alstublieft een geldige postcode in." );

            }

        }

    }

    return $result;
}   

add_filter( 'wpcf7_validate_text*', 'custom_postcode_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text', 'custom_postcode_validation_filter', 10, 2 );

I think it's probably something with this line: if(!preg_match('/^([0-9]{4})\\([^a-Z]{2})$/', $bapostcode)) {.

So I updated the answer after getting some help. This is what I have now:

function custom_postcode_validation_filter($result,$tag){

    $name = $tag->name;

    if($name == 'ba-postcode'){

        $bapostcode = $_POST['ba-postcode'];

        if($bapostcode != '') {

            $regex = "/^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{2}$/i";

if(!preg_match( $regex, $bapostcode)) {
    $result->invalidate( $tag, "Vul alstublieft een geldige postcode in." );
}

    return $result;
}   

add_filter( 'wpcf7_validate_text*', 'custom_postcode_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_text', 'custom_postcode_validation_filter', 10, 2 );
    }
 }

It's still not working. What am I missing?

Also I would like that if the user fills in the field without capital letters, the textfield transforms them automatically.

Any advice is appreciated!


Solution

  • Okay I got it done with this code:

    function custom_postcode_validation_filter($result,$tag){
    
        $name = $tag->name;
    
        if($name == 'ba-postcode'){
    
            $bapostcode = $_POST['ba-postcode'];
    
            if($bapostcode != '') {
    
                if(!preg_match('/^([1-9]{1})([0-9]{3})([\s]{0,1})([a-zA-Z]{2})$/', $bapostcode)) {
    
                    $result->invalidate( $tag, "Vul alstublieft een geldige postcode in." );
    
                }
    
            }
    
        }
    
        return $result;
    }   
    
    add_filter( 'wpcf7_validate_text*', 'custom_postcode_validation_filter', 10, 2 );
    add_filter( 'wpcf7_validate_text', 'custom_postcode_validation_filter', 10, 2 );