Jump to content

Negative integers


Porl123

Recommended Posts

I've been making this function which checks if the value isn't a decimal, which works. Then I've put is_numeric in there and checked that the value is >= 1 because all I want the user to enter is a whole, numeric, positive number. But for some reason it still allows the user to enter values with a minus on the end e.g. 010000000000000-

I'm not really sure at all why it allows them to do that. If someone could help me out with what I'm missing it would be greatly appreciated. Thanks

Link to comment
Share on other sites

I've been making this function which checks if the value isn't a decimal, which works. Then I've put is_numeric in there and checked that the value is >= 1 because all I want the user to enter is a whole, numeric, positive number. But for some reason it still allows the user to enter values with a minus on the end e.g. 010000000000000-

I'm not really sure at all why it allows them to do that. If someone could help me out with what I'm missing it would be greatly appreciated. Thanks

Numbers which end with a minus are not negatives, negatives start with a minus.

 

Also when you do

$var = (int)$var;

(int) will remove any non-numeric characters from $var, eg

$var = '123abc456';
echo (int) $var;

PHP will return $var as 123

Link to comment
Share on other sites

I agree with Wildteen and Darkwater that you can convert the value to an integer and then just validate that it is greater than 0.

 

However, in some instances changing the users entered value like that can be problematic and you should have them correct it themselves. The easiest solution for that (in my opinion) would be a simple regular expression check

<?php

  if (!preg_match("/[^\d]/", $_POST['thevalue'])) { 
    echo "Valid";
  } else {
    echo "Not Valid";
  }

?>

 

The value must contain only numbers (0-9) and cannot contain decimals, negative signs, etc.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.