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

仅允许使用javascript和mootools在字段中输入int和float,javascript,mootools,Javascript,Mootools,我需要一些关于如何只允许在表单输入字段中输入int或float的指导。验证必须在密钥更新事件上进行。我遇到的问题是,例如,当输入1.2时,keyup事件函数中的检查会看到1。这不是一个数字 以下是我的代码: document.id('inputheight').addEvent('keyup', function(e) { this.value = this.value.toFloat(); if (this.value == 'NaN') { this.valu

我需要一些关于如何只允许在表单输入字段中输入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

这真的很有效。很好。我必须掌握正则表达式。值得一提的是,在执行此操作时,还必须确保有相应的服务器端检查,因为恶意用户可以并且将绕过该检查。