简体   繁体   English

Javascript / Jquery验证keypress / keydown上的十进制输入

[英]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. 我正在采用jQuery.keydown的方法,检查密钥是什么,如果密钥不在允许列表中,则使用event.preventDefault()。 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? 我遇到过这个问题,但是我不能流利使用正则表达式并且不确定这是否符合我的需求: jquery - 验证按键上的字符?

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. 使用该方法,当键入00时,期望00.00的正则表达式将停止用户,因为在加密时检查正则表达式。

Thanks 谢谢

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. 或者 ,我们可以在用户“离开”字段后使用on change事件更新此内容,这样用户仍然可以使用箭头键浏览文本。

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/ 小提琴: http//jsfiddle.net/shannonhochkins/eu7P9/

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) 你应该做的是使用类似zurb的textchanged事件 - 无论输入模式如何(键,粘贴,拖放,等等)都会准确触发

http://www.zurb.com/playground/jquery-text-change-custom-event 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. textchanged处理程序中,您可以放入适当的正则表达式来处理小数。

I have used e.which to validate the decimal numbers 我用e.which来验证十进制数

$(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/ 链接:: HTTP://jsfiddle.net/rTr2w/

using Shannon 's answer, I provide the following simple JS code: 使用Shannon的答案,我提供了以下简单的JS代码:

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/ 看到这个在行动: 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/ 示例: http//jsfiddle.net/SnakeEyes/eu7P9/3/

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

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