karmacrow Posted March 9, 2007 Share Posted March 9, 2007 Hi, this should be an easy one but still somehow im not getting it. I want to validate a zip code (a german one) which is made up of exactly 5 numbers. So i use the following code function fValidate_Postcode($postcode) { if( ereg("[0-9]{5}", $postcode)===false ) { return false; } return true; } but for some reason it returns true when the postcode is longer than 5 numbers. Why? I thought the {5} should make the regular expression only match if there are exactly 5 numbers? Thanks for your help! Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 9, 2007 Share Posted March 9, 2007 if( ereg("^[0-9]{5}$", $postcode)===false ) Quote Link to comment Share on other sites More sharing options...
redarrow Posted March 9, 2007 Share Posted March 9, 2007 <?php if(! is_numeric($postcode){ echo"sorry your post code is not a number"; } $x=strlen($postcode); if($x >5){ echo"sorry your post code is more then 5 numbers long"; }elseif( ereg("^[0-9]{5}$", $postcode)){ //code here }else{ echo"sorry your postcode is wrong"; } ?> Quote Link to comment Share on other sites More sharing options...
obsidian Posted March 9, 2007 Share Posted March 9, 2007 but for some reason it returns true when the postcode is longer than 5 numbers. Why? I thought the {5} should make the regular expression only match if there are exactly 5 numbers? The reason it doesn't work is that you are not declaring your string to match only those five digits. You are simply matching any string with five consecutive digits within it. So, yours would actually match something like "abc012345" as well as "09_23456zz?". To match the five and only the five digits, use something like this: <?php if (!preg_match('|^[\d]{5}\z|', $zip)) { // Your zipcode doesn't match! } ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.