Solved

PHP  simple comparison (validation) question

Posted on 2008-06-18
4
224 Views
Last Modified: 2010-04-21
I have a web form input text field where i want the user to enter a 5 digit zipcode.
What is the best way (in php, not JS) to make sure it's 5 digits 0-9
I've tried  < and > comparisons, but characters evidently get converted to integers and some short strings can fall within the 0-99999 range.

thanks
0
Comment
Question by:willsherwood
4 Comments
 
LVL 24

Accepted Solution

by:
glcummins earned 167 total points
ID: 21814616
There are a number of PHP ZIP code validation scripts available, which helps you to avoid reinventing the wheel. One common one is here:

http://www.hotscripts.com/Detailed/46060.html
0
 
LVL 82

Assisted Solution

by:hielo
hielo earned 167 total points
ID: 21814619
assuming the name of your field is zipcode:
if( preg_match('/^\d\d\d\d\d([-]\d\d\d)?$/', $_REQUEST['zipcode']) )
{
 $zip = $_REQUEST['zipcode'];
 echo "$zip  is valid";
}
0
 
LVL 48

Assisted Solution

by:hernst42
hernst42 earned 166 total points
ID: 21814627
try to validate:

if (!preg_match('/^\d{5}$/', $zipcodeToValidate) {
 // invalid zip code
}
0
 

Author Closing Comment

by:willsherwood
ID: 31468445
thanks to you all.  (simultaneously)
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question