Jquery验证:带正/负的浮点数,小数点为6位2

Jquery Validation : Floating number filed with Positive/Negative with 6 digit 2 decimal

本文关键字:小数点 6位 浮点数 验证 带正 Jquery      更新时间:2023-09-26

我试图限制我的文本字段,使其采用带有6个数字和2个小数限制的浮点数字。

示例123456.12222222.22.

我需要在小数点前最多有6位数字。数字可以是正数也可以是负数。

我尝试过:https://jsfiddle.net/wuL34dto/

$('.number').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
   ((event.which < 48 || event.which > 57) &&
   (event.which != 0 && event.which != 8))) {
       event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
    setTimeout(function() {
        if ($this.val().substring($this.val().indexOf('.')).length > 3) {
            $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
        }
    }, 1);
}
if ((text.indexOf('.') != -1) &&
    (text.substring(text.indexOf('.')).length > 2) &&
    (event.which != 0 && event.which != 8) &&
    ($(this)[0].selectionStart >= text.length - 2)) {
        event.preventDefault();
}      
});

提前谢谢。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://www.jasny.net/bootstrap/dist/js/jasny-bootstrap.min.js"></script>
<input class="inputmask">
<script>
$('.inputmask').inputmask({
  mask: '999999.99'
})
</script>

text.match(^[0-9]{6}('.[0-9]{1,2})?$).length > 0

未测试此模式

或添加jquery函数

$.fn.extend({
    checkinput:function() {
      return text.match(^[0-9]{6}('.[0-9]{1,2})?$).length > 0;
});

用法:

if(text.checkinput())