繁体   English   中英

使用JavaScript仅允许数字中的十进制字段

[英]Allowing decimal in numbers only field with JavaScript

我有一个函数,用于将表单输入限制为仅数字或数字和小数,具体取决于字段。 允许使用小数和数字很容易,但是我试图更进一步,只允许一个小数,同时还要确保十进制不是该字段中的第一个字符。 我已经成功地只允许了一个小数,并且我也已经做到了,所以仅当“ 0”是第一位时才允许使用十进制,但是由于任何原因,当任何数字为第一位时我都不能允许它使用十进制。 如果我发表大量的if声明,我可以使它起作用,但是我试图避免这种情况。 有什么建议么?

            // this allows only one decimal, and only if the first character of the field is a zero
            else if ((('.').indexOf(keychar) > -1) && field == document.form.start_pay && document.form.start_pay.value.indexOf('.') <= -1 && document.form.start_pay.value.charAt(0) == ('0')){
                return true;
            }
/^((?:\d\.\d)|(?:\d+))$/.test(document.form.start_pay)

将涵盖您所有的情况。 (要经过11000.78.3和任何其他排列你能想到的,但不允许.31.21 ...等)

逐行:

/ #Begin regular expression
    ^ #Starting at the beginning of the string
    ( #For group #1
        (?: #Match
            \d\.\d #A number followed by a literal . (\.) followed by a number
        )
    | #Or
        (?: #Match
            \d+ #A number one or more times
        )
    ) #End group 1
    $ #Followed by the end of the string
/ #End regular expression

更改为:

        else if ((('.').indexOf(keychar) > -1) && field == document.form.start_pay && document.form.start_pay.value.indexOf('.') <= -1 && /[0-9]+/.test(document.form.start_pay.value.charAt(0))){
            return true;
        }

变更:

document.form.start_pay.value.charAt(0) == ('0')

至 :

!isNaN(document.form.start_pay.value.charAt(0))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM