简体   繁体   中英

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. 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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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