简体   繁体   English

jQuery输入字段验证

[英]jquery input field validation

I'm trying to validate user input data using jquery. 我正在尝试使用jquery验证用户输入数据。 Here is the code I use. 这是我使用的代码。

$('#ole').keypress(function(event) {
              if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
              }
            });

The code above allows only integers and a single dot. 上面的代码仅允许整数和单个点。 What I need is to allow only two integers after the dot. 我需要的是在点后仅允许两个整数。

How to achieve that ? 如何实现呢?

TRY with this 尝试与此

HTML HTML

<input id="ole" class="decimal">​

jQuery jQuery的

$(document).on('change blur','.decimal',function() {
      var amt = parseFloat(this.value);
      if(isNaN(amt)) {
        $(this).val('');
      }
      else {
         $(this).val(amt.toFixed(2));
      }
    });

working DEMO working DEMO

Use a Regex expression and round the decimals: 使用正则表达式并四舍五入小数:

$('#ole').on('blur', function()
{
    var val = $(this).val();

    if (val.match(/^\d+\.{0,1}\d+$/)) 
    {
        // Convert to int if needed
        val = parseInt(val);

        val = Math.round(val *100)/100; // Round to 2 decimals
        $(this).val(val);
    }
});​

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

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