How to allow only one decimal point for input of t

2019-06-24 06:43发布

问题:

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);
}

回答1:

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:



回答2:

<input type="text" pattern="\d+\.?\d?(?!\d)" />


回答3:

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



回答4:

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);
}