is_int, is_numeric, is_float, and HTML form validation

拥有回忆 提交于 2019-12-21 05:08:07

问题


A select field on my HTML form may yield 1 to 5 (integers). Using is_int rejects it every time, because the $_POST['rating'] is viewed as a string.

After consulting the PHP Manual, it seems is_numeric() && !is_float() is the proper way to validate for an integer in this case.

But I want to be certain, so please confirm or fire away at my logic.


回答1:


I would use is_numeric(), because user input always comes in as a string (as far as I know).

Another way to guarantee something is an integer is to cast it...

$id = (int) $id;



回答2:


I would probably use something like this:

$value = filter_var(
  $_POST['rating'], 
  FILTER_VALIDATE_INT, 
  array('options' => array('min_range' => 1, 'max_range' => 5))); 

filter_var() will return either boolean false if the value is non-integer or out-of-range, or the valid value itself (as an integer.)




回答3:


You could use the following regular expression:

preg_match('/^[0-9]{1,}$/', $value);

I does validate digits with leading zeros though...




回答4:


is_int requires the input content is a integer. is_numeric requires the input content is a integer or a string including just 0-9.

but I am wondering the result if I put a number that is bigger than PHP_INT_MAX as the parameter into the above 2 functions.




回答5:


You can always cast it as an int.

$rating = (int)$_POST['rating'];

This will remove the need to validate it (even though you should always validate form data). It may reduce your steps is what I'm getting at.




回答6:


If you're testing for digits only (what an integer usually is ;)), I tend to use ctype_digit instead of is_int. That way, you won't lose data through casting, and you can just use a string:

<?php
$_POST['foo'] = '42';
echo ctype_digit( (string) $_POST['foo'] ) ? 'yep' : 'nope';

That'll output "yep".




回答7:


if you want to know if $_POST['rating'] is an int before you even try to cast do use is_numeric() && !is_float() as you have. This will tell you if the string is an int or not. If you just cast to an int and there is a non numeric all the numbers before the first letter in the string is turned into an int.

x = 457h
print (int)x

outputs 457

x = h56
print (int)x

outputs 0



来源:https://stackoverflow.com/questions/5486926/is-int-is-numeric-is-float-and-html-form-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!