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

时间:2010-06-22 21:56:36

标签: javascript forms decimal if-statement

我有一个函数用于将表单输入限制为仅限数字,或者根据字段限制数字和小数。允许小数和数字很容易,但我试图更进一步,只允许一个小数,同时还要确保小数不是字段中的第一个字符。我已经成功地只允许一个小数,并且我也已经使它只有“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;
            }

3 个答案:

答案 0 :(得分:3)

/^((?:\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

答案 1 :(得分:2)

将其更改为:

        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;
        }

答案 2 :(得分:0)

更改:

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

致:

!isNaN(document.form.start_pay.value.charAt(0))
相关问题