• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 351
  • Last Modified:

Checking if field contains numbers


How can I tell if $FORM{count} only contains numbers, therefore no letters etc.

Thanks in advance,

Graeme Sandwell
1 Solution
You want to check whether a string represents a valid number. This is a common problem when validating input, as in a CGI script.

This problem gets to the heart of what we mean by a number. Even things that sound simple, like integer, make you think hard about what you will accept ("Is a leading + for positive numbers optional, mandatory, or forbidden?").

You must decide what you will and will not accept. Then, construct a regular expression to match those things alone. Here are some precooked solutions  for most common cases.

## Sample value.

## Eliminate any leading and trailing spaces from the variable
$FORM{count}=~ s/^\s+//;
$FORM{count}=~ s/\s+$//;

## Now check...
if ($FORM{count}!~ /^\d+$/){ # rejects -3
  print "not a natural number\n";

if ($FORM{count}!~ /^-?\d+$/){ ## rejects +3
  print "not an integer\n";

if ($FORM{count}!~ /^[+-]?\d+$/){
  print "not an integer\n";

if ($FORM{count}!~ /^-?\d+\.?\d*$/){ ## rejects .2
  print "not a decimal number\n";

if ($FORM{count}!~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/){
  print "not a decimal number\n";
perldoc -q "How do I determine whether a scalar is a number/whole/integer/float"
graemesandwellAuthor Commented:
Thanks for all the time you put into your answer!  I was looking for a number > 0.

Thanks again!

Graeme Sandwell
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now