只允许使用javascript和mootools在字段中输入int和float

Only allowing ints and floats to be entered into field with javascript and mootools

本文关键字:输入 int float 字段 mootools 许使用 javascript      更新时间:2023-11-17

我需要某种方向来指导如何只允许在表单输入字段中输入int或float。验证必须在密钥打开事件上进行。我遇到的问题是,例如,当输入1.2时,keyup事件函数中的检查会看到不是数字的1.

这是我的代码:

document.id('inputheight').addEvent('keyup', function(e) {
    this.value = this.value.toFloat();
    if (this.value == 'NaN') {
        this.value = 0;
    }         
});

感谢您的帮助!

您可以简单地清除keyup上字段的值。像这样的东西应该可以做到:

this.value = this.value.replace(/([^'d.]+)?(('d*'.?'d*)(.*)?$)/, "$3");

正则表达式会立即用它遇到的第一个数字字符串替换该值。

([^'d.]+)?  // optionally matches anything which is not
            // a number or decimal point at the beginning
('d*'.?'d*) // tentatively match any integer or float number
(.*)?$      // optionally match any character following
            // the decimal number until the end of the string