Checking if field is empty AND using !is_numeric

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
DiscoDave
Forum Newbie
Posts: 4
Joined: Mon Oct 26, 2009 8:15 am

Checking if field is empty AND using !is_numeric

Post by DiscoDave »

Hi lads,

Need to be able to display an error message (using isset?) that says "Cant leave field blank" when someone clicks on submit after leaving the field blank. The problem is that I'm also using the !is numeric function and that has an error message of "please enter numbers only" . Problem is that if someone leaves the field blank, the !is_numeric function picks up that there are no numbers before isset does and therefore outputs "please enter numbers" .

Anyone have any idea's how to fix this ?
My code is :

Code: Select all

<?php
function validate_form()
{
   $entered_grade = trim($_REQUEST['entergrade']);
 
   $error = '';
            if (! isset($entered_grade))
         {
            $error .=
            "<span class=\"error\">You cannot leave the grade blank. Enter a mark between 0 and 100.</span><br>";
         }
if (! is_numeric($entered_grade))
   {
      $error .=
      "<span class=\"error\">Invalid Input. You must enter a NUMBER between 0 and 100</span><br>";
   }
      if ($entered_grade >=101 )
      {
         $error .=
         "<span class=\"error\">Invalid Input. The marks must be between 0 and 100.</span><br>";
      }
 
 
   return $error;
}
 
Thanks for all help,
Dave
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Checking if field is empty AND using !is_numeric

Post by papa »

elseif((! is_numeric($entered_grade))

?
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Checking if field is empty AND using !is_numeric

Post by Mark Baker »

use isempty() rather than !isset()... because in doing $entered_grade = trim($_REQUEST['entergrade']); you're setting $entered_grade.

Use elseif as stated by papa

and you're probably better using ctype rather than isnumeric() to test for a numeric value.... isnumeric() returns true to a whole host of values that you probably don't want

And fix your logic for the range of values if the entered grade is a number
DiscoDave
Forum Newbie
Posts: 4
Joined: Mon Oct 26, 2009 8:15 am

Re: Checking if field is empty AND using !is_numeric

Post by DiscoDave »

Im on the site 5 mins and i'm already seeing helpful advice.

Thank you lads for the help.
Just for other readers of this post, the function is " empty " and not "isempty" .

Thanks again lads,
Dave
Post Reply