How to allow only one decimal point for input of t

2019-06-24 06:51发布

I am using a input of type number in which it allows multiple decimal points so i have tried using the regex not to allow more than one decimal point but even after using the regex i am facing the same issue can anyone tell me how to allow only one decimal point in input of type number in ionic1

Html:

<input stopccp focus-me class="inputContainer trade_input" type="number" name="" ng-model="vm.total_amount[$index]" ng-change="vm.onTotalCost()" limit-char limit="5" ng-keyup="vm.decimalcheck(vm.total_amount[$index])"  >

Regex in function:

function decimalcheck (element) {
  $log.log('decimalcheck got called', element);
  var regex = /\d*\.?\d?/g;
  return regex.exec(element);
}

4条回答
走好不送
2楼-- · 2019-06-24 07:04
<input type="text" pattern="\d+\.?\d?(?!\d)" />
查看更多
Explosion°爆炸
3楼-- · 2019-06-24 07:06

Try this Regex:

^\d*\.?\d+$

Click for Demo

Explanation:

  • ^ - Start of String
  • \d*- 0+ digits
  • \.?- 0 or 1 decimal point
  • \d+- 1+ digits(thus making it mandatory to have atleast one digit after the decimal point, if it is present)
  • $- End of String

OUTPUT: enter image description here

查看更多
干净又极端
4楼-- · 2019-06-24 07:08

I think you just miss start(^) and end($) operator

function decimalcheck (element) {
  $log.log('decimalcheck got called', element);
  var regex = /^\d*\.?\d?$/g;
  return regex.exec(element);
}
查看更多
淡お忘
5楼-- · 2019-06-24 07:10

Script

$('.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 > 1) &&
        (event.which != 0 && event.which != 8) &&
        ($(this)[0].selectionStart >= text.length - 1)) {
            event.preventDefault();
    }      
});

$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
    if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
        e.preventDefault();
        $(this).val(text.substring(0, text.indexOf('.') + 3));
   }
}
else {
        e.preventDefault();
     }
});

HTML

<input type="text" class="number" />

Here is your answer

查看更多
登录 后发表回答