简体   繁体   English

只允许使用javascript和mootools将整数和浮点数输入字段

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

I require some sort of direction with how to only allow either an int or float to be entered into a form input field. 我需要某种关于如何只允许将int或float输入到表单输入字段中的指示。 The validation must happen on the key up event. 验证必须在按键事件上进行。 The problem I am having is that when entering, for example, 1.2 the check within the keyup event function sees 1. which is not a number. 我遇到的问题是,例如在输入1.2时,keyup事件函数中的检查会看到1.这不是数字。

Here is the code I have: 这是我的代码:

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

Any help is appreciated! 任何帮助表示赞赏!

You could simply clean up the value of the field on keyup. 您可以简单地清理keyup字段的值。 Something like this should do the trick: 这样的事情应该可以解决问题:

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

The regular expression instantly replaces the value with the first numeric string it encounters. 正则表达式立即用遇到的第一个数字字符串替换该值。

([^\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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM