jQuery 文本框整数验证 [英] jQuery Textbox Whole Number Validation
问题描述
我有下面的脚本,我用它来验证输入以验证没有文本的文本框,它也很有用地加倍以只允许 0 到 10 之间的数字,最多有 3 个小数位.
I have the script below, which I use to validate input to validate a textbox for no text, and it also usefully doubles to only allow a number between 0 and 10 with up to 3 decimal places.
$('.sourceValidation').keyup(function () {
if (!this.value.match(/^(([0-9]|10)(\.\d{1,3})?)?$/)) {
this.value = this.value.replace(/[^0-9\.]/g, '').substring(0,5);}})
我不完全确定这段代码,但我如何修改它,以便它验证 0 到 99 之间的输入(仅限整数),没有文本,没有小数点.
I am not entirely sure of this code, but how do I rework it so that it will validate an input between 0 and 99 (whole numbers only), no text, no decimal points.
推荐答案
$('.sourceValidation').keyup(function () {
if (!this.value.match(/^([0-9]{0,2})$/)) {
this.value = this.value.replace(/[^0-9]/g, '').substring(0,2);
}
});
关键部分是从
/^(([0-9]|10)(\.\d{1,3})?)?$/
到
/^([0-9]{0,2})$/
..这是一个允许 0、1 或 2 位数字的正则表达式.然而,它允许前导零,例如 01
、09
- 甚至 00
.我不知道这在您的情况下是否可以接受.
..which is a regex which will allow 0, 1 or 2 digits. It will however allow leading zeroes eg 01
, 09
- or even 00
. I don't know if this is acceptable in your situation.
replace
函数是说 [^0-9]/g
- 这意味着 - 替换任何不是 (^
) adigit (0-9
) 并通过整个字符串(g
- 全局)执行此操作.然后将其修剪为最多 2 个字符 (substring(0,2)
).
The replace
function is saying [^0-9]/g
- which means - replace anything that is not (^
) a digit (0-9
) and do it through the whole string (g
- global). It is then trimming it to 2 characters max (substring(0,2)
).
这篇关于jQuery 文本框整数验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!