2012-07-19 84 views
0

我需要某种方向,以便只允许在表单输入字段中输入int或float。验证必须在关键事件中进行。我遇到的问题是,在输入时,例如,1.2 keyup事件功能中的检查看到1.这不是一个数字。只允许整数和浮点数与javascript和mootools输入字段

这里是我的代码:

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

任何帮助表示赞赏!

回答

1

你可以简单地清理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 
+0

这真的很好。很好。我必须掌握正则表达式。 – beingalex 2012-07-19 12:38:30

+0

值得一提的是,当您这样做时,您还必须确保有相应的服务器端检查,因为恶意用户可以绕过该检查。 – 2012-07-19 13:03:14

相关问题