Jump to content

Postcode validation


wiggst3r

Recommended Posts

I'm trying to implement postcode validation (UK) in a form I've wrote.

All works fine, If I include a space, e.g. AB12 3CD, but If I have the whole thing written as AB123CD, I can't get it to work and I get a validation error.

 

My code to display the error is as follows:

 

		
if(!str_replace(' ', '', $v->valid_postcode($data['post_code'])))
{
$errors[] = "You must enter a valid postcode";
}

 

Postcode validation function:

 

function valid_postcode($postcode) {
  $postcode = strtoupper($postcode);
  if(ereg("((GIR 0AA)|(TDCU 1ZZ)|(ASCN 1ZZ)|(BIQQ 1ZZ)|(BBND 1ZZ)"
."|(FIQQ 1ZZ)|(PCRN 1ZZ)|(STHL 1ZZ)|(SIQQ 1ZZ)|(TKCA 1ZZ)"
."|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]"
."|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))"
."|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})", $postcode)) {
      return $postcode;
} else {
     return FALSE;
}

 

I want it, so no matter what I type, AB12 3CD or AB123CD, it lets me use this.

 

Any ideas where I'm going wrong?

 

Thanks

 

 

Link to comment
https://forums.phpfreaks.com/topic/126611-postcode-validation/
Share on other sites

If there isn't a space, put one in first. The second part is always 3 characters.

 

<?php
$str = 'AB123CD';

if (strpos($str,' ')===false)
{
    $str = substr($str, 0, strlen($str)-3) . ' ' . substr($str, -3);
}

echo $str;
?>

Link to comment
https://forums.phpfreaks.com/topic/126611-postcode-validation/#findComment-654934
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.