Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate an unsigned number in PHP?

Tags:

validation

php

I'm not sure how to handle this one, and I've tried what to me are the most obvious solutions, but so far none have proved entirely satisfactory. I must be overlooking something very simple.

I have a form with an input of type text:

<input type="text" name="album_id">

I want to validate the input so the users only enters unsigned integer...

$required = array(); // required or invalid input

$tmp = trim($_POST['album_id']);

if (!is_int((int)$tmp)) {
   $required['album'] = 'The album id must contain a positive numeric value only.';
}

So far I've use !is_numeric($tmp) but a user can enter 9.2 or '1e4' and it will validate... so that one doesn't work.

I've also tried !is_int((int)$tmp) but for some reason, that one doesn't work (maybe it should but i'm doing it wrong...). I tried ctype_digit with no success. I'm probably overlooking something but not sure what.

How can I validate an unsigned number in php? No floats, negative numbers, etc... only a simple unsigned number (1 to n).

like image 241
Marco Avatar asked Dec 12 '22 14:12

Marco


1 Answers

If you want to check if some variable only contains digits (which seems to be what you want, here), you'll probably have to go with ctype_digit().


Not sure what you tried, but something like this should work :

$tmp = trim($_POST['album_id']);
if (ctype_digit($tmp)) {
    // $tmp only contains digits
}
like image 68
Pascal MARTIN Avatar answered Jan 02 '23 01:01

Pascal MARTIN