dqenv99518 2014-03-19 19:59
浏览 120
已采纳

php验证阻止输入0作为值?

I have a field in a form for entering the number of masters titles won by a Tennis player. Some players have 0 titles. Even though my validation checks for an empty field I cannot enter 0. What changes do I need to make to allow 0 to be entered?

if (empty($_POST["masters"])) {
    $has_errors = true;
    $mastersErr = "Enter 0-10";
} else {
    $masters = validate_input($_POST["masters"]);
}
  • 写回答

1条回答 默认 最新

  • dongliuzhuan1219 2014-03-19 20:00
    关注

    use if ($_POST["masters"] === '') { to check for empty string

    this is because

    empty($variable) returns true if $variable equals false, null, '' (empty string) or 0

    you can't use $_POST['masters'] == '' because in PHP statement 0 == '' is true

    you have to use === operator

    please also mind $_POST['xxx'] === 0 will never work because values in $_POST are strings


    Anyway if you want user to put number between 0-10 I would suggest to do this check

    if(is_numeric($var) && ($var >= 0) && ($var <= 10) && (intval($var) == $var))
    {
        // OK
    }else
    {
       // not OK
    }
    

    This is because space character will pass $_POST["masters"] === '' check.

    In validation you should always create if statements keeping in mind to check "is this value OK", not "is this value bad". For example if you want to validate email you dont' check "is value empty" "is value a number" "is value a float", you check "is value a email"|

    is_numeric() is good, because

    • is_numeric('') is false
    • is_numeric(' ') is false
    • is_numeric(0) is true

    but beware! because

    • is_numeric('0.1') is also true...

    ...so you need another check:

    (intval($var) == $var) - this is how you make sure user entered integer (not float) number

    PHP Manual:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题