十进制验证允许通过JavaScript小数点的关键preSS事件后两位数字 [英] Decimal Validation allowing two digits after the Decimal Point on Keypress Event through Javascript

查看:134
本文介绍了十进制验证允许通过JavaScript小数点的关键preSS事件后两位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要限制用户在重点preSS event.Please帮助使用纯JavaScript小数点后输入两个数字。

I need to restrict the user to enter two digits after the decimal point using pure Javascript on Key press event.Please help..

EX:123.45 - 正确>
    123.45.6 - >错误

EX: 123.45 ->Correct 123.45.6 ->Incorrect

function checkDec(el) {
    var ex = /^[0-9]+\.?[0-9]*$/;
    if (ex.test(el.value) == false) {
        el.value = el.value.substring(0, el.value.length - 1);
    }
}

<asp:TextBox ID="txttest0" runat="server" onkeydown="checkDec(this);" ></asp:TextBox>

我试过这种方式,但需要有它在关键preSS。 (

I tried this way,but need to have it in Keypress. :(

推荐答案

也许你可以只用parseFloat修正值:

Maybe you can just correct the value using parseFloat:

<input onchange="this.value = parseFloat(this.value) || ''" type="text" />

我改成了的onchange,因为否则就prevent你打字。在所有。然而,这意味着如果模糊输入只会验证一次。

I changed it to onchange because otherwise it would prevent you from typing a . at all. This however means it will only validate once when you blur the input.

修改

这样便?

JS:

function validateFloatKeyPress(el, evt) {

    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode != 46 && charCode > 31
        && (charCode < 48 || charCode > 57)) {
        return false;
    }

    if (charCode == 46 && el.value.indexOf(".") !== -1) {
        return false;
    }

    return true;
}

HTML

<input onkeypress="return validateFloatKeyPress(this, event)" type="text" />

这篇关于十进制验证允许通过JavaScript小数点的关键preSS事件后两位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆