Javascript/Jquery validating decimal input on keypress/keydown

和自甴很熟 提交于 2019-12-22 18:10:09

问题


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


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




回答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/




回答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/




回答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/



来源:https://stackoverflow.com/questions/12659756/javascript-jquery-validating-decimal-input-on-keypress-keydown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!