Javascript/Jquery validating decimal input on keypress/keydown

29,548

Solution 1

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.

Solution 2

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/

Solution 3

I have used e.which to validate the decimal numbers

$(document).ready(function () { 
    var isEnable=true;
$(".only-number-period").live('keydown', function (e) {
    //isEnable = (e.which != 110) ? false : true;
        if( ((e.which == 9) || (e.which == 46) || (e.which == 8) || (e.which == 110) || (e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105))){
            if(isEnable ==false && e.which ==110){return false;}
        }else{
        return false
        }  
    if (isEnable == true) {            
    isEnable=(e.which ==110)?false:true;
        }
    });
});​

link::http://jsfiddle.net/rTr2w/

Solution 4

using Shannon's answer, I provide the following simple JS code:

jQuery('.numbersOnly').keyup(function () {
    if(($(this).val().split(".")[0]).indexOf("00")>-1){
        $(this).val($(this).val().replace("00","0"));
    } else {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
    }
});

See this in action: http://jsfiddle.net/SnakeEyes/eu7P9/2/

update To avoid multiple . symbol, use the following code:

jQuery('.numbersOnly').keyup(function (e) {
    if(($(this).val().split(".")[0]).indexOf("00")>-1){
        $(this).val($(this).val().replace("00","0"));
    } else {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
    }

    if($(this).val().split(".")[2] != null || ($(this).val().split(".")[2]).length ){
        $(this).val($(this).val().substring(0, $(this).val().lastIndexOf(".")));
    }   
});

Example: http://jsfiddle.net/SnakeEyes/eu7P9/3/

Share:
29,548
Matthew Grima
Author by

Matthew Grima

Updated on July 27, 2022

Comments

  • Matthew Grima
    Matthew Grima almost 2 years

    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

  • Shannon Hochkins
    Shannon Hochkins over 11 years
    Thanks mate, also you'll not be able to use the arrow keys to navigate through text, you'll have to add custom functionality for that, I just don't have the time!
  • Matthew Grima
    Matthew Grima over 11 years
    I can do that on change rather than keyup, so it would cover pasting etc. But apart from that, that regex allows multiple decimal points.
  • Snake Eyes
    Snake Eyes over 11 years
    @MatthewGrima: See my updated code. It avoids multiple dots . in your input
  • Matthew Grima
    Matthew Grima over 11 years
    I've used this as I found it very good and easy to use and also applied Snake Eyes's answer in the way I needed it. Thanks