Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/Jquery validating decimal input on keypress/keydown

I'm trying to find a way to validate a text input on key press, I want to allow numbers only inside my text input including decimals.

I was taking the approach of using jQuery.keydown, and checking what the key was and using event.preventDefault() if the key was not in the allowed list. But since then I've read that keys aren't consistent throughout browsers and I'm also worries about different OS's.

I've come across this question but I'm not fluent in regex and not sure whether this would suit my needs: jquery - validate characters on keypress?

With that approach a regex that expects 00.00 would stop the user when 00. is typed in since the regex is checked upon key up.

Thanks

like image 827
Matthew Grima Avatar asked Jan 31 '26 08:01

Matthew Grima


2 Answers

If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

or, we can update this after the user has 'left' the field, with the on change event, this way the user can still navigate through the text with the arrow keys.

jQuery('.numbersOnly').on('change', function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This immediately lets the user know that they can't enter alpha characters, etc. rather than later during the validation phase.

You'll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.

Fiddle: http://jsfiddle.net/shannonhochkins/eu7P9/

like image 130
Shannon Hochkins Avatar answered Feb 01 '26 23:02

Shannon Hochkins


You should not rely on key events as that would mean the validation would fail if the user does a right-click -> paste with invalid characters.

What you should instead do is use something like zurb's textchanged event - which will accurately trigger regardless of the mode of input (key, paste, drag and drop, whatever)

http://www.zurb.com/playground/jquery-text-change-custom-event

Inside your textchanged handler, you can put in the appropriate regex to deal with decimals.

like image 35
techfoobar Avatar answered Feb 01 '26 22:02

techfoobar