【问题标题】:Test if field value is numeric and not empty [duplicate]测试字段值是否为数字且不为空 [重复]
【发布时间】:2012-12-13 20:49:06
【问题描述】:

可能重复:
Validate that a string is a positive integer

所以我想检查一个表单域是否为空,并允许它只有正数,没有空格或字母。到目前为止,我使用以下代码成功检查了该字段是否为空:

function validate(form) {
    var elements = form.elements;

    if (form.qty.value == "") {
        alert("Please enter the field");
        document.forms[0].qty.focus()
        document.forms[0].qty.select()
        return false;
    }

    return true;
}

表格中的某处:

<form action="addtocart.php" method ="post" onsubmit="return validate(this);" /> ...

但现在我想只允许数字以及检查该字段是否为空。我找到了一些脚本,但我不知道如何将代码合并到一个有效的脚本中。

【问题讨论】:

    标签: javascript html


    【解决方案1】:
    if (Number(form.qty.value) > 0) {
        // Only executes if value is a positive number.
    }
    

    请注意,如果值为空字符串,则语句将不会返回 true。 nullNaN(显然)和undefined 也是如此。数字的字符串表示形式被转换为它们的数字对应物。

    【讨论】:

    • 这在浮点数上计算为true,所以除非 OP 愿意为需要 1.5 个数量的客户切碎产品......
    • @MrCode - 他说“正数”。他没有在任何地方指定他需要一个整数。也许他是在按重量卖东西,他没有具体说明。
    • 无论如何,你总是可以添加类似number % 1 == 0;
    • 如果这是他想要的。但是,如果是这样的话,他将不得不这么说。
    【解决方案2】:

    你可以使用regexp
    你的模式是^\d+$

    ^ - 行首
    $ - 行尾
    \d - 数字
    + - 1次或多次

    if(mystr.match(/^\d+$/))
    {
        //
    }
    

    如果你需要第一个符号不是0,你应该写/^(0|[^1-9]\d*)/
    阅读正则表达式文档以了解此模式。

    【讨论】:

    • 不适用于"1e5" 之类的字符串或浮点值。 ("123,456" / "123.456")
    • aw...在这种情况下,其他答案会更好。
    【解决方案3】:

    尝试使用search() 函数和正则表达式。像这样:

    if (form.qty.value.search(/^([0-9\.]+)$/)==-1)
    {
    alert ("Please enter the field");
    document.forms[0].qty.focus()
    document.forms[0].qty.select()
    return false;
    }
    

    【讨论】:

    • 非常感谢,我是 js 的新手,这项工作正如我所愿!
    • 不适用于"1e5" 之类的字符串,也不适用于使用逗号作为分隔符的浮点值。 ("123,456")
    • 也不适用于无效:“1.2.3”
    【解决方案4】:

    检查以下答案:https://stackoverflow.com/a/10270826/783743

    在你的情况下,我会做以下事情:

    function validate(form) {
        return isPositive(+form.qty.value);
    }
    
    function isPositive(n) {
        return +n === n && n >= 0;
    }
    

    说明:

    1. 表达式+form.qty.value 将字符串强制转换为数字。如果字符串为空或不是数字,它将表示NaN
    2. 函数 isPositive 仅在 n 是数字 (+n === n) 并且大于或等于零 (n >= 0) 时返回正数。

    【讨论】:

    • 这似乎不适用于浮点值。另外,我建议解释一下按位运算的工作原理(例如传递参数时的+
    • @Cerbrus - 加号运算符 (+) 不是位运算符。它用于将原始值(布尔值、字符串或数字)强制转换为数字。函数isPositive 期望n 是一个数字。表达式 +n === n 仅在 n 是数字且不是 NaN 时才返回 true
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 2012-09-27
    • 1970-01-01
    • 2011-04-05
    • 2018-08-10
    • 2019-01-25
    • 2018-02-16
    相关资源
    最近更新 更多