我有一个函数,用于将表单输入限制为仅数字,或数字和小数,具体取决于字段。允许小数和数字很容易,但我试图更进一步,只允许一个小数,同时还要确保小数不是字段中的第一个字符。我已经成功地只允许一个小数,而且我也做到了,所以只有当“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)
将涵盖您的所有案例。 (应该传递 1
、100
、0.7
、8.3
和您能想到但不允许的任何其他排列 .3
, 1.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
关于javascript - 使用 JavaScript 允许数字字段中的小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097449/