2016-07-27 119 views
0

提起我試圖限制我的文本字段採用浮點數6個數字和2個小數限制。jquery驗證:浮動號碼與正/負與6位數字2小數

實施例123456.12,222222.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(); 
}  
}); 

在此先感謝。

+0

你應該學習正則表達式:-) – ADyson

回答

0

<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>

0
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())