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!
2
Answers
Okay I got it done with this code:
Try this regex expression, I have used it in a Dutch site which shares a similar structure.