2012-07-19 86 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

相關問題